FFT模板
我终于下定决心学习FFT了。
orzCHX,得出模板:
#include<cstdio> #include<cctype> #include<queue> #include<cmath> #include<cstring> #include<algorithm> #define rep(i,s,t) for(int i=s;i<=t;i++) #define dwn(i,s,t) for(int i=s;i>=t;i--) #define ren for(int i=first[x];i!=-1;i=next[i]) using namespace std; inline int read() { int x=0,f=1;char c=getchar(); for(;!isdigit(c);c=getchar()) if(c=='-') f=-1; for(;isdigit(c);c=getchar()) x=x*10+c-'0'; return x*f; } const int maxn=300010; const double PI=acos(-1.0); struct FFT { struct cox { double r,i; cox(double _r=0.0,double _i=0.0) {r=_r;i=_i;} cox operator + (const cox& b) const {return cox(r+b.r,i+b.i);} cox operator - (const cox& b) const {return cox(r-b.r,i-b.i);} cox operator * (const cox& b) const {return cox(r*b.r-i*b.i,r*b.i+i*b.r);} }f[maxn]; int len; void init(int* A,int Len,int L) { len=L;rep(i,0,Len-1) f[i]=cox(A[Len-i-1],0); } void cal(int tp) { int j=len>>1; rep(i,1,len-2) { if(i<j) swap(f[i],f[j]);int k=len>>1; while(j>=k) j-=k,k>>=1;j+=k; } double lm=-2*tp*PI; for(int i=2;i<=len;i<<=1) { cox wn(cos(lm/i),sin(lm/i)); for(int j=0;j<len;j+=i) { cox w(1,0); for(int k=j;k<j+(i>>1);k++) { cox u=f[k],v=w*f[k+(i>>1)]; f[k]=u+v;f[k+(i>>1)]=u-v;w=w*wn; } } } if(tp<0) rep(i,0,len-1) f[i].r/=len; } }a,b; void mul(int* A,int* B,int L1,int L2,int& L,int* ans) { L=1;while(L<L1<<1||L<L2<<1) L<<=1; a.init(A,L1,L);b.init(B,L2,L); a.cal(1);b.cal(1); rep(i,0,L-1) a.f[i]=a.f[i]*b.f[i]; a.cal(-1);rep(i,0,L-1) ans[i]=int(a.f[i].r+0.5); } int A[maxn],B[maxn],ans[maxn]; int main() { int L1=read()+1,L2=read()+1,L; rep(i,0,L1-1) A[i]=read(); rep(i,0,L2-1) B[i]=read(); mul(A,B,L1,L2,L,ans); while(L>L1+L2-1&&!ans[L-1]) L--; dwn(i,L-1,0) printf("%d ",ans[i]); return 0; }