fft模板
手写类:
#include<cstdio> #include<cmath> const int LEN=300000; const double pi=acos(-1); inline int read(){ int x=0;char ch=getchar();while(ch<'0'||ch>'9')ch=getchar(); while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+ch-'0',ch=getchar(); return x; } struct complex{ double r,v; complex(double a=0,double b=0):r(a),v(b){} inline complex operator+(const complex& b){return complex(r+b.r,v+b.v);} inline complex operator-(const complex& b){return complex(r-b.r,v-b.v);} inline complex operator*(const complex& b){return complex(r*b.r-v*b.v,v*b.r+r*b.v);} }; inline void swap(complex& a,complex& b){complex t(a);a=b;b=t;} int n,m,L,H,R[LEN]; complex a[LEN],b[LEN]; complex w[LEN]; int ans[LEN]; void FFT(complex* a,int f){ for(int i=0;i<L;i++)if(i<R[i])swap(a[i],a[R[i]]); for(int len=2;len<=L;len<<=1){ int l=len>>1; complex wn(cos(pi/l),f*sin(pi/l)); for(int i=1;i<l;i++) w[i]=w[i-1]*wn; for(int st=0;st<L;st+=len) for(int k=0;k<l;k++){ complex x=a[st+k],y=w[k]*a[st+k+(len>>1)]; a[st+k]=x+y,a[st+k+(len>>1)]=x-y; } } } int main(){ w[0].r=1; n=read()+1,m=read()+1; for(int i=0;i<n;i++) a[i]=read(); for(int i=0;i<m;i++) b[i]=read(); for(H=0,L=1;L<(n+m-1);H++)L<<=1; for(int i=0;i<L;i++) R[i]=(R[i>>1]>>1)|((i&1)<<(H-1)); FFT(a,1),FFT(b,1); for(int i=0;i<L;i++) a[i]=a[i]*b[i]; FFT(a,-1); for(int i=0;i<n+m-1;i++) printf("%d ",int(a[i].r/L+0.5)); return 0; }
内置:
#include<bits/stdc++.h> #define pi acos(-1) using namespace std; typedef complex<double> E; int n,m; E a[262145],b[262145]; void fft(E *x,int n,int type) { if(n==1)return; E l[n>>1],r[n>>1]; for(int i=0;i<n;i+=2) l[i>>1]=x[i],r[i>>1]=x[i+1]; fft(l,n>>1,type);fft(r,n>>1,type); E wn(cos(2*pi/n),sin(type*2*pi/n)),w(1,0),t; for(int i=0;i<n>>1;i++,w*=wn) t=w*r[i],x[i]=l[i]+t,x[i+(n>>1)]=l[i]-t; } int main() { scanf("%d%d",&n,&m); for(int i=0,x;i<=n;i++)scanf("%d",&x),a[i]=x; for(int i=0,x;i<=m;i++)scanf("%d",&x),b[i]=x; m=n+m;for(n=1;n<=m;n<<=1); fft(a,n,1);fft(b,n,1); for(int i=0;i<=n;i++)a[i]=a[i]*b[i]; fft(a,n,-1); for(int i=0;i<=m;i++) printf("%d ",(int)(a[i].real()/n+0.5)); return 0; }
递推:
#include<bits/stdc++.h> #define N 262145 #define pi acos(-1) using namespace std; typedef complex<double> E; int n,m,L; int R[N]; E a[N],b[N]; void fft(E *a,int f) { for(int i=0;i<n;i++)if(i<R[i])swap(a[i],a[R[i]]); for(int i=1;i<n;i<<=1) { E wn(cos(pi/i),f*sin(pi/i)); for(int p=i<<1,j=0;j<n;j+=p) { E w(1,0); for(int k=0;k<i;k++,w*=wn) { E x=a[j+k],y=w*a[j+k+i]; a[j+k]=x+y;a[j+k+i]=x-y; } } } } int main() { scanf("%d%d",&n,&m); for(int i=0,x;i<=n;i++)scanf("%d",&x),a[i]=x; for(int i=0,x;i<=m;i++)scanf("%d",&x),b[i]=x; m=n+m;for(n=1;n<=m;n<<=1)L++; for(int i=0;i<n;i++)R[i]=(R[i>>1]>>1)|((i&1)<<(L-1)); fft(a,1);fft(b,1); for(int i=0;i<=n;i++)a[i]=a[i]*b[i]; fft(a,-1); for(int i=0;i<=m;i++) printf("%d ",(int)(a[i].real()/n+0.5)); return 0; }