HDU2203 亲和串

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

 
Problem Description
人随着岁数的增长是越大越聪明还是越大越笨,这是一个值得全世界科学家思考的问题,同样的问题Eddy也一直在思考,因为他在很小的时候就知道亲和串如何 判断了,但是发现,现在长大了却不知道怎么去判断亲和串了,于是他只好又再一次来请教聪明且乐于助人的你来解决这个问题。
亲和串的定义是这样的:给定两个字符串s1和s2,如果能通过s1循环移位,使s2包含在s1中,那么我们就说s2 是s1的亲和串。
 
Input
本题有多组测试数据,每组数据的第一行包含输入字符串s1,第二行包含输入字符串s2,s1与s2的长度均小于100000。

 

Output
如果s2是s1的亲和串,则输出"yes",反之,输出"no"。每组测试的输出占一行。
 
Sample Input
AABCD CDAA ASD ASDF
 
Sample Output
yes no
 
 
 
正解:KMP
解题报告:
  KMP裸题,只需要把母串再复制一遍,然后跑KMP就可以了。
  联赛前复习模板...
 
 1 //It is made by ljh2000
 2 #include <iostream>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <cstdio>
 6 #include <cmath>
 7 #include <algorithm>
 8 #include <ctime>
 9 #include <vector>
10 #include <queue>
11 #include <map>
12 #include <set>
13 #include <string>
14 #include <stack>
15 using namespace std;
16 typedef long long LL;
17 const int MAXN = 200011;
18 char s[MAXN],ch[MAXN];
19 int f[MAXN],n,m;
20 
21 inline int getint(){
22     int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
23     if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
24 }
25 
26 inline void build(){
27     n=strlen(s); m=strlen(ch); int j; f[0]=f[1]=0;
28     for(int i=n;i<n+n;i++) s[i]=s[i-n]; n*=2;
29     for(int i=1;i<m;i++) {
30         j=f[i];    while(j && ch[j]!=ch[i]) j=f[j];
31         f[i+1]= (ch[j]==ch[i])?j+1:0;
32     }
33 }
34 
35 inline bool find(){
36     int j=0; if(n/2<m) return false;
37      for(int i=0;i<n;i++) {
38         while(j && s[i]!=ch[j]) j=f[j];
39         if(s[i]==ch[j]) j++;
40         if(j==m) return true;
41     }
42     return false;
43 }
44 
45 inline void work(){
46     while(scanf("%s",s)!=EOF) {
47         scanf("%s",ch); build();
48         if(find()) printf("yes
");
49         else printf("no
");
50     }
51 }
52 
53 int main()
54 {
55     work();
56     return 0;
57 }
原文地址:https://www.cnblogs.com/ljh2000-jump/p/6077914.html