KMP

自己YY的

 1 #include<cstdio> 
 2 #include<cstring>
 3 #include<cmath>
 4 #include<ctime>
 5 #include<iostream>
 6 #include<algorithm>
 7 #include<queue>
 8 #include<set>
 9 #define inf (0x7fffffff)
10 #define l(a) ((a)<<1)
11 #define r(a) ((a)<<1|1)
12 #define b(a) (1<<(a))
13 #define rep(i,a,b) for(int i=a;i<=(b);i++)
14 #define clr(a) memset(a,0,sizeof(a))
15 typedef long long ll;
16 typedef unsigned long long ull;
17 using namespace std;
18 int readint(){
19     int t=0,f=1;char c=getchar();
20     while(!isdigit(c)){
21         if(c=='-') f=-1;
22         c=getchar();
23     }
24     while(isdigit(c)){
25         t=(t<<3)+(t<<1)+c-'0';
26         c=getchar();
27     }
28     return t*f;
29 }
30 const int maxn=1000009,maxm=1000009;
31 int n,m,next[maxn];
32 char A[maxn],B[maxm];
33 void init(){
34     scanf("%s%s",A+1,B+1);
35     n=strlen(A+1);m=strlen(B+1);
36     next[0]=-1;
37     rep(i,2,n){
38         for(int t=next[i-1];t;t=next[t]) if(B[i]==B[t+1]){
39             next[i]=t+1;break;
40         }
41         if(!next[i]&&B[i]==B[1]) next[i]=1;
42     }
43 }
44 void cal(){
45     for(int i=1;i<=n-m+1;){
46         rep(j,1,m) if(i<=n-m+1){        
47                 if(A[i+j-1]!=B[j]){
48                 i+=j-1-next[j-1];//ÒÑÆ¥Åä-next 
49                 if(j>1) j=next[j-1];
50             }else if(j==m){
51                 printf("%d\n",i);
52                 i+=j-next[j];//ÒÑÆ¥Åä-next 
53                 break;
54             }
55         }
56     }
57     rep(i,1,m){
58         printf("%d",next[i]);
59         putchar(i==m?'\n':' ');
60     }
61 }
62 int main(){
63     init();
64     cal();
65     return 0;
66 }
View Code

 

posted @ 2017-11-20 22:02  ChenThree  阅读(157)  评论(0编辑  收藏  举报