两种办法,前者通过率要高一些,总是有问题(感觉第一个测试点不对???)
查看原帖
两种办法,前者通过率要高一些,总是有问题(感觉第一个测试点不对???)
602038
Goldkeys楼主2023/7/19 22:00

这个办法是逐个处理的(字符)

//P1308 [NOIP2011 普及组] 统计单词数

#include <stdio.h>
#include <iostream>
#include <bits/stdc++.h>
#include <string.h>

using namespace std;

void CutStrZeroAndGive(char* sz1,const char* sz2,int st,int end)	//make sz1 = sz2[(st~end)];
{
	for (int i=st,j=0;i<=end;i++,j++) {				//give values, include '\0'
		sz1[j] = sz2[i];
	}
	
	//end-st+1
	sz1[end-st+1] = 0;
	
	return;
}

//Ignore capitalization
bool IfStrEquel(char *sz1, char *sz2)
{
	if (strlen(sz1) != strlen(sz2)) {
		return false;
	}
	
	for (int i=0;i<strlen(sz1);i++) {
		if (sz1[i]==sz2[i] || ( ( 'a'<=sz1[i] & 'z'>=sz1[i] & sz1[i]==sz2[i]+('a'-'A') )  ||  ( 'A'<=sz1[i] & 'Z'>=sz1[i] & sz1[i]==sz2[i]+('A'-'a') )  )) {
			//printf("i=%d, sz1=%c, sz2=%c, sz1BIG=%c, sz2BIG=%c",i,sz1[i],sz2[i],);
		} else {
			return false;
		}
	}
	
	return true;
}

int main()
{
	char szFindObject[64];				//the sz what need to find.
	char szIn[102400];						//the sz what need to find in.
	
	scanf("%s\n",&szFindObject);
	//printf("first in: %s\n",szFindObject);
	
	//get input
	//scanf("%s",&szFindObject);			
	string sTimelySave;
	getline(cin,sTimelySave);
	
	//cout << "Beginning: " << sTimelySave << endl;
	CutStrZeroAndGive(szIn,sTimelySave.c_str(),0,strlen(sTimelySave.c_str()));
	
	//printf("Your input: %s\n", szIn);
	
	//
	int lastspace = -1;					//the position to save the last space where is.
	int sum = 0;
	int first_eq = -1;
	for (int i=0;i<=strlen(szIn);i++) {
		int aWordSize = 0;
		if (szIn[i] == ' ' || szIn[i] == '\0') {			//a word had judged end.
			aWordSize = i-lastspace;	//lenth of the word what are judging.
			char szJudgingWord[64];
			CutStrZeroAndGive(szJudgingWord, szIn, lastspace+1, i-1);
		
			//printf("[i=%d, lastspace=%d] deal with the word: %s\n",i,lastspace,szJudgingWord);
			
			if (IfStrEquel(szFindObject,szJudgingWord)) {
				//printf("FOUND!!!\n");
				sum++;
				if (first_eq == -1) {
					first_eq = lastspace+1;
				}
			}
			
			lastspace = i;
		}
		
	}
	
	if (sum!=0) {
		printf("%d %d\n",sum,first_eq);
	} else {
		printf("-1\n");
	}
	
	return 0;
}

这个办法是交给string的类成员函数来处理的,相对简单,但是通过率不高。

//P1308 [NOIP2011 普及组] 统计单词数

#include <bits/stdc++.h>

using namespace std;

int main()
{
	string f,a;
	getline(cin,f);
	getline(cin,a);
	transform(a.begin(),a.end(),a.begin(),::toupper);	//all small.
	transform(f.begin(),f.end(),f.begin(),::toupper);	//all small.
	int sum =0,p1 = -1,l = -1,c = a.find(" ");
	while (c!=-1) {
		string finding;
		finding = a.substr(l+1,c-1);
		if (finding.length() == f.length() & finding.find(f) == 0) {
			sum++;
			if (p1==-1) p1=l+1;
		}
		l = c;
		c = a.find(" ",l+1);
	}
	if (sum == 0) {
		cout << "-1";
	} else {
		cout << sum << " " << p1 << endl;
	}
	return 0;
}
2023/7/19 22:00
加载中...