hdu2203kmp匹配

拼接字符串即可解决移位的问题;

代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define dbg(args) cout<<#args<<":"<<args<<endl;
17 #define inf 0x3f3f3f3f
18 #define maxn 1000010
19 int n,m,t;
20 char s[maxn],p[maxn],nxt[maxn];
21 void getnxt()
22 {
23     nxt[0]=-1;
24     int i=-1,j=0;
25     while(j<strlen(p))
26     {
27         if(i==-1||p[i]==p[j])
28         {
29             i++,j++;
30             if(p[i]==p[j])nxt[j]=nxt[i];
31             else nxt[j]=i;
32         }
33         else i=nxt[i];
34      } 
35 }
36 void kmp()
37 {
38     int plen=strlen(p);
39     int slen=strlen(s);
40     int i=0,j=0;
41     while(i<slen)
42     {
43         if(j==-1||s[i]==p[j])i++,j++;
44         else j=nxt[j];
45         if(j==plen)
46         {
47             pf("yes\n");
48             return;
49         }
50     }
51     pf("no\n");
52 }
53 int main()
54 {
55     //freopen("input.txt","r",stdin);
56     //freopen("output.txt","w",stdout);
57     std::ios::sync_with_stdio(false);
58     while(scanf("%s %s",s,p)==2)
59     {
60         if(strlen(s)<strlen(p))pf("no\n");
61         else{
62             int len=strlen(s);
63             f(i,0,len-1)s[len+i]=s[i];//解除循环 
64             getnxt();
65             kmp();
66         }
67     }
68  } 

 

上一篇:hdu1908 逆序对


下一篇:[HAOI2008] 木棍分割 - dp,前缀和,双指针