[模板]洛谷T3375 KMP字符串匹配
这东西。。。算是半囫囵吞枣的理解了。。。总之板子背过就好了嘛QwQ~
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<cmath> 5 #include<ctime> 6 #include<cstdlib> 7 8 #include<string> 9 #include<stack> 10 #include<queue> 11 #include<vector> 12 #include<algorithm> 13 #include<map> 14 #include<set> 15 16 #define inf 2147483647 17 #define ri register int 18 #define ll long long 19 20 using namespace std; 21 22 inline void read(int &x){ 23 x=0; 24 char t=getchar(); 25 bool f=0; 26 27 while(t<'0' || t>'9'){ 28 if(t=='-')f=1; 29 t=getchar(); 30 } 31 32 while(t>='0' && t<='9'){ 33 x=(x<<3)+(x<<1)+t-'0'; 34 t=getchar(); 35 } 36 37 if(f)x=-x; 38 } 39 40 inline void getnext(); 41 inline void KMP(); 42 43 char s1[1000005]; 44 char s2[1000005]; 45 int l1,l2; 46 47 int next[1000005]; 48 49 int main(){ 50 scanf("%s",s1+1); 51 scanf("%s",s2+1); 52 53 l1=strlen(s1+1); 54 l2=strlen(s2+1); 55 56 getnext(); 57 58 KMP(); 59 60 for(ri i=1;i<=l2;i++)printf("%d ",next[i]); 61 62 return 0; 63 } 64 65 inline void getnext(){ 66 int j=0; 67 next[1]=0; 68 69 for(ri i=2;i<=l2;i++){ 70 while(j && s2[i]!=s2[j+1])j=next[j]; 71 if(s2[i]==s2[j+1])j++; 72 next[i]=j; 73 } 74 } 75 76 inline void KMP(){ 77 int j=0; 78 79 for(ri i=1;i<=l1;i++){ 80 while(j && s1[i]!=s2[j+1])j=next[j]; 81 if(s1[i]==s2[j+1])j++; 82 83 if(j==l2){ 84 printf("%d\n",i-j+1); 85 j=next[j]; 86 } 87 } 88 }