# 快速傅里叶变换 FFT 板子

1092人阅读 评论(0)

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int maxn = 410000;
const double pi=acos(-1);
struct E
{
double x,y;
E(){x=y=0;}
E(double a,double b){x=a;y=b;}
}a[maxn],b[maxn],c[maxn],w[maxn];
int id[maxn],an,bn,cn,n,ln;
E operator +(E x,E y){return E(x.x+y.x,x.y+y.y);}
E operator -(E x,E y){return E(x.x-y.x,x.y-y.y);}
E operator *(E x,E y){return E(x.x*y.x-x.y*y.y,x.x*y.y+x.y*y.x);}

void fft(E *s,int sig)
{
for(int i=0;i<n;i++)if(i<id[i])swap(s[i],s[id[i]]);
for(int m=2;m<=n;m<<=1)
{
int t=m>>1,tt=n/m;
for(int i=0;i<t;i++)
{
E wn=sig==1?w[i*tt]:w[n-i*tt];
for(int j=i;j<n;j+=m)
{
E tx=s[j],ty=s[j+t]*wn;
s[j]=tx+ty;
s[j+t]=tx-ty;
}
}
}
if(sig==-1)for(int i=0;i<n;i++)s[i].x/=(double)n;
}

int main()
{
scanf("%d%d",&an,&bn);an++;bn++;
for(int i=0;i<an;i++) scanf("%lf",&a[i].x);
for(int i=0;i<bn;i++) scanf("%lf",&b[i].x);

n=1;ln=0;while(n<(an+bn))ln++,n<<=1;
for(int i=0;i<n;i++) id[i]=id[i>>1]>>1|((i&1)<<(ln-1));
for(int m=2;m<=n;m<<=1)
{
int t=m>>1,tt=n/m;
for(int i=0;i<t;i++)
{
w[i*tt]=E(cos(i*2*pi/m),sin(i*2*pi/m));
w[n-i*tt]=E(cos(i*2*pi/m),sin(-i*2*pi/m));
}
}

fft(a,1);fft(b,1);
for(int i=0;i<n;i++) c[i]=a[i]*b[i];
fft(c,-1);
printf("%d",int(c[0].x+0.5));
for(int i=1;i<an+bn-1;i++)printf(" %d",int(c[i].x+0.5));
printf("\n");

return 0;
}


友链
个人资料
等级：
访问量： 14万+
积分： 6099
排名： 5028