bzoj 2194 快速傅立叶之二 —— FFT
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2194
如果把 a 序列翻转,则卷积得到的是 c[n-i],再把得到的 c 序列翻转即可。
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; typedef double db; int const xn=(1<<18); db const Pi=acos(-1.0); int n,lim,l,c[xn],rev[xn]; struct com{db x,y;}a[xn],b[xn]; com operator + (com a,com b){return (com){a.x+b.x,a.y+b.y};} com operator - (com a,com b){return (com){a.x-b.x,a.y-b.y};} com operator * (com a,com b){return (com){a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x};} int rd() { int ret=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=0; ch=getchar();} while(ch>='0'&&ch<='9')ret=(ret<<3)+(ret<<1)+ch-'0',ch=getchar(); return f?ret:-ret; } void fft(com *a,int tp) { for(int i=0;i<lim;i++) if(i<rev[i])swap(a[i],a[rev[i]]); for(int mid=1;mid<lim;mid<<=1) { com wn=(com){cos(Pi/mid),tp*sin(Pi/mid)}; for(int j=0,len=(mid<<1);j<lim;j+=len) { com w=(com){1,0}; for(int k=0;k<mid;k++,w=w*wn) { com x=a[j+k],y=w*a[j+mid+k]; a[j+k]=x+y; a[j+mid+k]=x-y; } } } } int main() { n=rd()-1; for(int i=0;i<=n;i++)a[n-i].x=rd(),b[i].x=rd(); lim=1; while(lim<=n+n)lim<<=1,l++; for(int i=0;i<lim;i++) rev[i]=((rev[i>>1]>>1)|((i&1)<<(l-1))); fft(a,1); fft(b,1); for(int i=0;i<lim;i++)a[i]=a[i]*b[i]; fft(a,-1); for(int i=0;i<=n;i++)c[n-i]=(int)(a[i].x/lim+0.5); for(int i=0;i<=n;i++)printf("%d\n",c[i]); return 0; }