洛谷P3375 【模板】KMP字符串匹配 kmp模板
洛谷P3375 【模板】KMP字符串匹配
kmp模板
1 #include <bits/stdc++.h> 2 #define LL long long 3 #define GG int 4 #define For(i, j, k) for(register int i=j; i<=k; i++) 5 #define Dow(i, j, k) for(register int i=j; i>=k; i--) 6 using namespace std; 7 inline GG read() { 8 GG x = 0, f = 1; 9 char ch = getchar(); 10 while(ch<'0'||ch>'9') { if(ch=='-') f = -1; ch = getchar(); } 11 while(ch>='0'&&ch<='9') { x = x*10+ch-48; ch = getchar(); } 12 return x * f; 13 } 14 void write(GG x) { 15 if(x<0) putchar('-'), x = -x; 16 if(x>9) write(x/10); 17 putchar(x%10+48); 18 } 19 inline void writeln(GG x) { write(x); putchar('\n'); } 20 21 const int N = 1000011; 22 int len1, len2; 23 int nxt[N]; 24 char s1[N], s2[N]; 25 26 void kmp() { 27 nxt[1] = 0; 28 For(i, 2, len2) { 29 int x = nxt[i-1]; 30 while(x && s2[i] != s2[x+1]) 31 x = nxt[x]; 32 if(s2[i] == s2[x+1]) ++x; 33 nxt[i] = x; 34 } 35 int x = 0; 36 s2[len2+1] = '#'; // 不存在的符号 37 For(i, 1, len1) { 38 while(x && s1[i] != s2[x+1]) 39 x = nxt[x]; 40 if(s1[i] == s2[x+1]) ++x; 41 if(x == len2) printf("%d\n", i-len2+1); 42 } 43 } 44 45 int main() { 46 scanf("%s", s1+1); scanf("%s", s2+1); 47 len1 = strlen(s1+1); len2 = strlen(s2+1); 48 kmp(); 49 For(i, 1, len2) printf("%d ", nxt[i]); 50 }