KMP模板,就不解釋了ios
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 #define int long long 7 #define maxn 1000000+10 8 #define INF 9187201950435737471 9 #define rep(i,s,e) for(register int i=s;i<=e;++i) 10 #define dwn(i,s,e) for(register int i=s;i>=e;--i) 11 using namespace std; 12 inline int read() 13 { 14 int x=0; 15 bool f=1; 16 char c=getchar(); 17 for(; !isdigit(c); c=getchar()) if(c=='-') f=0; 18 for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+c-'0'; 19 if(f) return x; 20 return 0-x; 21 } 22 inline void write(int x) 23 { 24 if(x<0){putchar('-');x=-x;} 25 if(x>9)write(x/10); 26 putchar(x%10+'0'); 27 } 28 int j,len1,len2; 29 char A[maxn],B[maxn]; 30 int p[maxn]; 31 void init() 32 { 33 j=0; 34 p[1]=0; 35 rep(i,2,len2) 36 { 37 while(j>0&&B[i]!=B[j+1]) j=p[j]; 38 if(B[i]==B[j+1]) ++j; 39 p[i]=j; 40 } 41 } 42 signed main() 43 { 44 scanf("%s",A+1); 45 scanf("%s",B+1); 46 len1=strlen(A+1); 47 len2=strlen(B+1); 48 init(); 49 j=0; 50 rep(i,1,len1) 51 { 52 while(j>0&&A[i]!=B[j+1]) j=p[j]; 53 if(A[i]==B[j+1]) ++j; 54 if(j==len2) 55 { 56 write(i-len2+1); 57 putchar('\n'); 58 j=p[j]; 59 } 60 } 61 rep(i,1,len2) write(p[i]),putchar(' '); 62 return 0; 63 }
請各位大佬斧正(反正我不認識斧正是什麼意思)git