啃了两天的算导配合着各路大神的博客,终于把FFT搞定了,在这里记录一下模板,方便日后使用(原题:UOJ 34)
代码:
#define INF 0x3f3f3f3f //int=1061109567,if num is 5, will trans to long type
#define MOD 10000000009
#define PI 3.14159265358979
#define scint(x) scanf("%d",&x)
#define scdb(x) scanf("%lf",&x)
#define pint(x) printf("%d",x)
#define pdb(x) printf("%lf",x)
#define per(i,x,y) for(int i=x;i<y;i++)
#define pere(j,x,y) for(int j=x;j<=y;j++)
#define rep(i,x,y) for(int i=x;i>y;i--)
#define repe(j,x,y) for(int j=x;j>=y;j--)
#define mem0(x) memset(x,0,sizeof x)
#define mem(x,y) memset(x,y,sizeof x)
#include <bits/stdc++.h> //test before contest
#include <complex>
typedef long long LL;
typedef std::complex<double> cd;
const int maxn = 2e6+233;
using namespace std;
int rev[maxn];
cd a[maxn],b[maxn];
void get_rev(int bit){
for(int i=0;i<(1<<bit);i++)
rev[i]=(rev[i>>1]>>1)|((i&1)<<(bit-1));
}
void fft(cd *a,int n,int idft){
for(int i=0;i<n;i++){
if(i<rev[i]) swap(a[i],a[rev[i]]);
}
for(int step=1;step<n;step<<=1){
cd wn=exp(cd(0,idft*PI/step));
for(int j=0;j<n;j+=step<<1){
cd wnk(1,0);
for(int k=j;k<j+step;k++){
cd x=a[k];
cd y=wnk*a[k+step];
a[k]=x+y;
a[k+step]=x-y;
wnk*=wn;
}
}
}
if(idft==-1){
for(int i=0;i<n;i++){
a[i]/=n;
}
}
}
int main(){
#ifdef Local
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
int n,m;
while(scanf("%d%d",&n,&m)==2){
mem0(a);
mem0(b);
for(int i=0;i<=n;i++){
int tmp;
scint(tmp);
a[i]=tmp;
}
for(int i=0;i<=m;i++){
int tmp;
scint(tmp);
b[i]=tmp;
}
int bit=1,s=2;
for(bit=1;(1<<bit)<=n+m;bit++)s<<=1;
get_rev(bit);
fft(a,s,1);
fft(b,s,1);
for(int i=0;i<s;i++) a[i]*=b[i];
fft(a,s,-1);
for(int i=0;i<=n+m;i++){
int tmp=(int)(a[i].real()+0.5);
printf("%d ",tmp);
}
printf("\n");
}
}