hdu 2203 亲和串 (kmp)
hdu 2203 题目链接 题意:给定字符串A(一个环),和字符串B,问B是否在A中出现过。
思路:环的问题。。复制一遍到末尾就好了。。出于严谨的考虑。。我们只复制n-1个字符。
以及要记得判断文本串的长度是否大于等于模板串,如果小于,直接判断no//然而题目数据太水,没判也过了
/* ***********************************************
Author :111qqz
Created Time :2016年08月12日 星期五 00时56分28秒
File Name :code/hdu/2203.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <stack>
8#include <set>
9#include <map>
10#include <string>
11#include <cmath>
12#include <cstdlib>
13#include <deque>
14#include <ctime>
15#define fst first
16#define sec second
17#define lson l,m,rt<<1
18#define rson m+1,r,rt<<1|1
19#define ms(a,x) memset(a,x,sizeof(a))
20typedef long long LL;
21#define pi pair < int ,int >
22#define MP make_pair
23using namespace std;
24const double eps = 1E-8;
25const int dx4[4]={1,0,0,-1};
26const int dy4[4]={0,-1,1,0};
27const int inf = 0x3f3f3f3f;
28const int N=1E5+7;
29char a[N],b[N];
30int n;
31int nxt[N];
32void getnxt(char *s)
33{
34 int n = strlen(s);
35 int i = 0 ;
36 int j = -1;
37 nxt[0] = -1;
38 while (i<n)
39 if (j==-1||s[i]==s[j]) nxt[++i]=++j;
40 else j = nxt[j];
41}
1bool kmp(char *a,char *b)
2{
3 int n = strlen(a);
4 int m = strlen(b);
5 getnxt(b);
6 int i = 0;
7 int j = 0 ;
8 while (i<n)
9 {
10 if (j==-1||a[i]==b[j]) i++,j++;
11 else j = nxt[j];
if (j==m) return true;
}
1 return false;
2}
3int main()
4{
5 #ifndef ONLINE_JUDGE
6 freopen("code/in.txt","r",stdin);
7 #endif
8 while (~scanf("%s %s",a,b))
9 {
10 int len1 = strlen(a);
11 int len2 = strlen(b);
12 if (len1<len2)
13 {
14 puts("no");
15 continue;
16 }
17 // cout<<"a:"<<a<<" b:"<<b<<" len1:"<<len1<<endl;
18 for ( int i = 0 ; i < len1-1 ; i++)
19 a[i+len1] = a[i];
20 // cout<<"now a:"<<a<<endl;
1 if (kmp(a,b))
2 puts("yes");
3 else puts("no");
4 ms(a,0); //记得清空。。。
5 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}