【 HDU - 5007 】E - Post Robot (KMP)

题目:

DT is a big fan of digital products. He writes posts about technological products almost everyday in his blog.

But there is such few comments of his posts that he feels depressed all the day. As his best friend and an excellent programmer, DT asked you to help make his blog look more popular. He is so warm that you have no idea how to refuse. But you are unwilling to read all of his boring posts word by word. So you decided to write a script to comment below his posts automatically.

After observation, you found words “Apple” appear everywhere in his posts. After your counting, you concluded that “Apple”, “iPhone”, “iPod”, “iPad” are the most high-frequency words in his blog. Once one of these words were read by your smart script, it will make a comment “MAI MAI MAI!”, and go on reading the post.

In order to make it more funny, you, as a fan of Sony, also want to make some comments about Sony. So you want to add a new rule to the script: make a comment “SONY DAFA IS GOOD!” when “Sony” appears.
Input
A blog article described above, which contains only printable characters(whose ASCII code is between 32 and 127), CR(ASCII code 13, ‘\r’ in C/C++), LF(ASCII code 10, ‘\n’ in C/C++), please process input until EOF. Note all characters are case sensitive.

The size of the article does not exceed 8KB.
Output
Output should contains comments generated by your script, one per line.
Sample Input
Apple bananaiPad lemon ApplepiSony
233
Tim cook is doubi from Apple
iPhoneipad
iPhone30 is so biiiiiiig Microsoft
makes good App.
Sample Output
MAI MAI MAI!
MAI MAI MAI!
MAI MAI MAI!
SONY DAFA IS GOOD!
MAI MAI MAI!
MAI MAI MAI!
MAI MAI MAI!


代码:

#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
int Next[1000000]; //next数组
string key[]={
    
    "Apple","iPhone","iPod","iPad","Sony","MAI MAI MAI!","SONY DAFA IS GOOD!"};//字符串数组
void getNext(string s)
{
    
    
	int len=s.length();
	fill(Next,Next+len,0);
	int j=-1;
	Next[0]=-1;
	for(int i=1;i<len;i++)
	{
    
    
		while(j!=-1 && s[i]!=s[j+1]){
    
    
			j=Next[j];
		}
		if(s[i]==s[j+1]) j++;
		Next[i]=j;
	}
}

int kmp(string s,string s1)
{
    
    
	getNext(s1);
	int len1=s.length();
	int len2=s1.length();
	int j=-1;
	for(int i=0;i<len1;i++)
	{
    
    
		while(j!=-1 && s[i]!=s1[j+1]){
    
     //没匹配上不断往前,直到找到或-1为止
			j=Next[j];
		}
		if(s[i]==s1[j+1]) j++;
		if(j==len2-1) return 1; //匹配完,返回true
	}
	return 0;
}

int main()
{
    
    
	string s;
	while(cin>>s) //一个一个单词输入
	{
    
    
		for(int i=0;i<4;i++)  //与数组下标0-3比较
			if(kmp(s,key[i])) cout<<key[5]<<endl;
		if(kmp(s,key[4])) cout<<key[6]<<endl; //数组下标4比较
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45260385/article/details/108201805
今日推荐