1. 程式人生 > >【FFT&NTT 總結】

【FFT&NTT 總結】

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<complex>
#define Maxn 262145
#define pi acos(-1)
using namespace std;

struct P
{
    double x,y;
    P() {x=y=0;}
    P(double x,double y):x(x),y(y){}
    friend P operator + (P x,P y) {return P(x.x+y.x,x.y+y.y);}
    friend P operator - (P x,P y) {return P(x.x-y.x,x.y-y.y);}
    friend P operator * (P x,P y) {return P(x.x*y.x-x.y*y.y,x.x*y.y+x.y*y.x);}
}a[Maxn],b[Maxn];

int nn;
int R[Maxn];
void fft(P *a,int f)
{
    for(int i=0;i<nn;i++) if(i<R[i]) swap(a[i],a[R[i]]);
    for(int i=1;i<nn;i<<=1)
    {
        P wn(cos(pi/i),f*sin(pi/i));
        for(int j=0;j<nn;j+=i<<1)
        {
            P w(1,0);
            for(int k=0;k<i;k++,w=w*wn)
            {
                P x=a[j+k],y=w*a[j+k+i];
                a[j+k]=x+y;a[j+k+i]=x-y;
            }
        }
    }
}
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=0;i<=n;i++) scanf("%lf",&a[i].x);
    for(int i=0;i<=m;i++) scanf("%lf",&b[i].x);
    int ll=0;nn=1;
    while(nn<=n+m) ll++,nn<<=1;
    for(int i=0;i<nn;i++) R[i]=(R[i>>1]>>1)|((i&1)<<(ll-1));
    fft(a,1);fft(b,1);
    for(int i=0;i<=nn;i++) a[i]=a[i]*b[i];
    fft(a,-1);
    for(int i=0;i<=n+m;i++) printf("%d ",(int)(a[i].x/nn+0.5));
    return 0;
}