题意:给定一个主串和一个模式(都只含有ATCG),求模式在主串中出现的次数
但是匹配的时候有一个偏移量K,即在用t[i]匹配s[j]的时候 只要s[j-k]---s[j+k]中有字符t[i]就算匹配;
这里用了FFT
参考:http://blog.csdn.net/u013368721/article/details/45565729
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cmath> #include <vector> using namespace std; const double PI = acos(-1.0); struct complex { double r,i; complex(double _r = 0.0,double _i = 0.0) { r = _r; i = _i; } complex operator +(const complex &b) { return complex(r+b.r,i+b.i); } complex operator -(const complex &b) { return complex(r-b.r,i-b.i); } complex operator *(const complex &b) { return complex(r*b.r-i*b.i,r*b.i+i*b.r); } }; void change(complex y[],int len) { int i,j,k; for(i = 1, j = len/2;i < len-1; i++) { if(i < j)swap(y[i],y[j]); k = len/2; while( j >= k) { j -= k; k /= 2; } if(j < k) j += k; } } void fft(complex y[],int len,int on) { change(y,len); for(int h = 2; h <= len; h <<= 1) { complex wn(cos(-on*2*PI/h),sin(-on*2*PI/h)); for(int j = 0;j < len;j+=h) { complex w(1,0); for(int k = j;k < j+h/2;k++) { complex u = y[k]; complex t = w*y[k+h/2]; y[k] = u+t; y[k+h/2] = u-t; w = w*wn; } } } if(on == -1) for(int i = 0;i < len;i++) y[i].r /= len; } const int N = 300005; char s[N], t[N], ss[5] = "ATCG"; complex x1[N<<1],x2[N<<1], res[N<<1]; int sum[N<<1]; int ls, lt, k; void solve(char c, int len){ memset(sum,0,sizeof(int)*len); memset(x1,0,sizeof(complex)*len); memset(x2,0,sizeof(complex)*len); for(int i = 0; i < ls; i++){ if(i == 0){ sum[i] = (s[i] == c); } else { sum[i] = sum[i-1] + (s[i] == c); } } for(int i = 0; i < ls; i++){ int l = max(0,i-k); int r = min(ls-1,i+k); if(l == 0){ x1[i] = complex(sum[r]>0,0); } else { x1[i] = complex((sum[r]-sum[l-1])>0,0); } } for(int i = 0; i < lt; i++){ x2[i] = complex(t[i] == c,0); } fft(x1,len,1); fft(x2,len,1); for(int i = 0; i < len; i++)res[i] = res[i] + x1[i] * x2[i]; } int main(){ while(~scanf("%d%d%d",&ls, <, &k)){ scanf("%s%s",s,t); int len = 1; while(len < (ls+lt+1))len<<=1; reverse(t, t+lt); for(int i = 0; i < 4; i++){ solve(ss[i],len); } fft(res, len, -1); int ans = 0; for(int i = 0; i < len; i++){ ans += (res[i].r+0.5) >= lt; } printf("%d\n",ans); } return 0; }