1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include <bits/stdc++.h> using namespace std; #define eps 1e-6 #define MS 1000009 #define LL long long
int n,m; char s1[MS], s2[MS]; int kmps2[MS]; int h1, h2; double A[MS], B[MS], S[MS]; double sumB, qzA[MS], jjSA[MS<<1];
typedef complex<double> comp; const double PI = acos(-1); const int N = (1<<21)+10; int lim, r[N]; comp a[N], b[N];
void fft(comp * a, int type) { for(int i = 0; i < lim; i ++) if(i < r[i]) swap(a[i], a[r[i]]); for(int i = 1; i < lim; i <<= 1) { comp x(cos(PI / i), type * sin(PI / i)); for(int j = 0; j < lim; j += (i << 1)) { comp y(1, 0); for(int k = 0; k < i; k ++, y *= x) { comp p = a[j + k], q = y * a[j + k + i]; a[j + k] = p + q; a[j + k + i] = p - q; } } } }
void get(double *c1, int n, double *c2, int m){ for(int i = 0; i <= n; i ++) a[i] = c1[i]; for(int i = 0; i <= m; i ++) b[i] = c2[i]; int l = 0; for(lim = 1; lim <= n + m; lim <<= 1) ++ l; for(int i = 0; i < lim; i ++) r[i] = (r[i >> 1] >> 1) | ((i & 1) << (l - 1)); fft(a, 1), fft(b, 1); for(int i = 0; i <= lim; i ++) a[i] *= b[i]; fft(a, -1); for(int i = 0; i <= n + m; i ++) jjSA[i] = (LL)(0.5 + a[i].real() / lim); }
void kmp(char *s, int len){ for(int i=1,j=0;i<len;i++){ while(j && s[i] != s[j]) j = kmps2[j-1]; if(s[i] == s[j]) j++; kmps2[i] = j; } }
int main() { scanf("%s",s1); getchar(); scanf("%s",s2); getchar(); int h1 = strlen(s1), h2 = strlen(s2); for(int i=0;i<h1;i++) A[i] = s1[i]-'a'+1; for(int i=0;i<h2;i++) B[i] = s2[i]-'a'+1; for(int i=0;i<h2;i++) S[i] = B[h2-i-1]; for(int i=0;i<h2;i++) sumB += B[i]*B[i]; qzA[0] = A[0]*A[0]; for(int i=1;i<h1;i++) qzA[i] = qzA[i-1] + A[i]*A[i]; get(S, h2-1, A, h1-1); for(int x=h2-1;x<h1;x++){ double P; if(x == h2-1) P = sumB + qzA[x] - jjSA[x]*2; else P = sumB + qzA[x] - qzA[x-h2] - jjSA[x]*2; if(abs(P) < eps){ printf("%d\n",x-h2+2); } } kmp(s2, h2); for(int i=0;i<h2;i++){ printf("%d ",kmps2[i]); } return 0; }
|