# bzoj4259: 残缺的字符串

https://www.lydsy.com/JudgeOnline/problem.php?id=4259

f[i+m-1]=Σ （a[i+j]-b[m-1-j]）^2 * a[i+j] * b[m-1-j]

FFT优化

#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N=(1<<20)+2;

const double eps=1e-9;

const double pi=acos(-1);

char s1[N],s2[N];
int t1[N],t2[N];

int rev[N];

double f[N];

struct Complex
{
double x,y;
Complex(double x_=0,double y_=0):x(x_),y(y_){}
Complex operator + (Complex P)
{
return Complex(x+P.x,y+P.y);
}
Complex operator - (Complex P)
{
return Complex(x-P.x,y-P.y);
}
Complex operator * (Complex P)
{
return Complex(x*P.x-y*P.y,x*P.y+y*P.x);
}
};
typedef Complex E;

E a[N],b[N];

int pos[N];

void fft(E *a,int len,int ty)
{
for(int i=0;i<len;++i)
if(i<rev[i]) swap(a[i],a[rev[i]]);
for(int i=1;i<len;i<<=1)
{
E wn(cos(pi/i),ty*sin(pi/i));
for(int p=i<<1,j=0;j<len;j+=p)
{
E w(1,0);
for(int k=0;k<i;++k,w=w*wn)
{
E x=a[j+k],y=a[j+k+i]*w;
a[j+k]=x+y; a[j+k+i]=x-y;
}
}
}
if(ty==-1)
{
for(int i=0;i<len;++i) a[i].x/=len;
}
}

int main()
{
// freopen("data.in","r",stdin);
// freopen("my.out","w",stdout);
int n,m;
scanf("%d%d",&m,&n);
scanf("%s%s",s2,s1);
reverse(s2,s2+m);
for(int i=0;i<n;++i)
if(s1[i]!='*') t1[i]=s1[i]-'a'+1;
for(int i=0;i<m;++i)
if(s2[i]!='*') t2[i]=s2[i]-'a'+1;

int num=n+m-1,len=1,bit=0;
while(len<num) len<<=1,bit++;
for(int i=0;i<len;++i) rev[i]=(rev[i>>1]>>1)|((i&1)<<bit-1);

for(int i=0;i<n;++i) a[i].x=t1[i]*t1[i]*t1[i],a[i].y=0;
for(int i=n;i<len;++i) a[i].x=a[i].y=0;
for(int i=0;i<m;++i) b[i].x=t2[i],b[i].y=0;
for(int i=m;i<len;++i) b[i].x=b[i].y=0;
fft(a,len,1); fft(b,len,1);
for(int i=0;i<len;++i) a[i]=a[i]*b[i];
fft(a,len,-1);
for(int i=0;i<num;++i) f[i]+=a[i].x;

for(int i=0;i<n;++i) a[i].x=t1[i],a[i].y=0;
for(int i=n;i<len;++i) a[i].x=a[i].y=0;
for(int i=0;i<m;++i) b[i].x=t2[i]*t2[i]*t2[i],b[i].y=0;
for(int i=m;i<len;++i) b[i].x=b[i].y=0;
fft(a,len,1); fft(b,len,1);
for(int i=0;i<len;++i) a[i]=a[i]*b[i];
fft(a,len,-1);
for(int i=0;i<num;++i) f[i]+=a[i].x;

for(int i=0;i<n;++i) a[i].x=t1[i]*t1[i],a[i].y=0;
for(int i=n;i<len;++i) a[i].x=a[i].y=0;
for(int i=0;i<m;++i) b[i].x=t2[i]*t2[i],b[i].y=0;
for(int i=m;i<len;++i) b[i].x=b[i].y=0;
fft(a,len,1); fft(b,len,1);
for(int i=0;i<len;++i) a[i]=a[i]*b[i];
fft(a,len,-1);
for(int i=0;i<num;++i) f[i]-=a[i].x*2;

int ans=0;
for(int i=0;i+m-1<n;++i)
if(f[i+m-1]<0.5) pos[++ans]=i;
printf("%d\n",ans);
for(int i=1;i<=ans;++i) printf("%d ",pos[i]+1);
} 

posted @ 2018-03-31 11:03  TRTTG  阅读(157)  评论(0编辑  收藏  举报