hdu 2203 亲和串 (kmp)

hdu 2203 题目链接 题意:给定字符串A(一个环),和字符串B,问B是否在A中出现过。

思路:环的问题。。复制一遍到末尾就好了。。出于严谨的考虑。。我们只复制n-1个字符。

以及要记得判断文本串的长度是否大于等于模板串,如果小于,直接判断no//然而题目数据太水,没判也过了

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年08月12日 星期五 00时56分28秒
 4File Name :code/hdu/2203.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <stack>
14#include <set>
15#include <map>
16#include <string>
17#include <cmath>
18#include <cstdlib>
19#include <deque>
20#include <ctime>
21#define fst first
22#define sec second
23#define lson l,m,rt<<1
24#define rson m+1,r,rt<<1|1
25#define ms(a,x) memset(a,x,sizeof(a))
26typedef long long LL;
27#define pi pair < int ,int >
28#define MP make_pair
29using namespace std;
30const double eps = 1E-8;
31const int dx4[4]={1,0,0,-1};
32const int dy4[4]={0,-1,1,0};
33const int inf = 0x3f3f3f3f;
34const int  N=1E5+7;
35char a[N],b[N];
36int n;
37int nxt[N];
38void getnxt(char *s)
39{
40    int n = strlen(s);
41    int i = 0 ;
42    int j = -1;
43    nxt[0] = -1;
44    while (i<n)
45	if (j==-1||s[i]==s[j]) nxt[++i]=++j;
46	else j = nxt[j];
47}
48
49bool kmp(char *a,char *b)
50{
51    int n = strlen(a);
52    int m = strlen(b);
53    getnxt(b);
54    int i = 0;
55    int j = 0 ;
56    while (i<n)
57    {
58	if (j==-1||a[i]==b[j]) i++,j++;
59	else j = nxt[j];
60
61	if (j==m) return true;
62    }
63
64    return false;
65}
66int main()
67{
68	#ifndef  ONLINE_JUDGE 
69	freopen("code/in.txt","r",stdin);
70  #endif
71	while (~scanf("%s %s",a,b))
72	{
73	    int len1 = strlen(a);
74	    int len2 = strlen(b);
75	    if (len1<len2)
76	    {
77		puts("no");
78		continue;
79	    }
80	   // cout<<"a:"<<a<<" b:"<<b<<" len1:"<<len1<<endl;
81	    for ( int i = 0 ; i  < len1-1 ; i++)
82		a[i+len1] = a[i];
83	 //   cout<<"now a:"<<a<<endl;
84
85	    if (kmp(a,b))
86		puts("yes");
87	    else puts("no");
88	    ms(a,0); //记得清空。。。
89	}
90
91  #ifndef ONLINE_JUDGE  
92  fclose(stdin);
93  #endif
94    return 0;
95}