[模板]FFT

郝神并没有令我明白这个。

但是巨神的题解太强了

 

#include <iostream>
#include <complex>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=2097153;
const double pi=acos(-1.0);
struct complexd{
    double x,y;
    complexd (double xx=0,double yy=0){x=xx,y=yy;}
    complexd operator + (const complexd &rhs) const {return complexd(x+rhs.x,y+rhs.y);}
    complexd operator - (const complexd &rhs) const {return complexd(x-rhs.x,y-rhs.y);}
    complexd operator * (const complexd &rhs) const {return complexd(x*rhs.x-y*rhs.y,x*rhs.y+y*rhs.x);}
};
inline int rd() {
    static int x;x=0;static char ch;ch=getchar();
    while(!isdigit(ch)) ch=getchar();
    while(isdigit(ch)) x=x*10+(ch^48),ch=getchar();
    return x;
}
int n,m,l,r[N];
void fft(complexd *b,short tag) {
    for(int i=0;i<n;i++) if(i<r[i]) swap(b[i],b[r[i]]);
    for(int mid=1;mid<n;mid<<=1) {
        complexd tp(cos(pi/mid),tag*sin(pi/mid));
        for(int j=0;j<n;j+=mid<<1) {
            complexd w(1,0);
            for(int k=0;k<mid;k++,w=w*tp) {
                complexd x=b[j+k],y=w*b[j+mid+k];
                b[j+k]=x+y;
                b[j+mid+k]=x-y;
            }
        }
    }
}
complexd a[N],b[N];
int main() {
    n=rd(),m=rd();
    for(int i=0;i<=n;i++) a[i].x=rd();
    for(int j=0;j<=m;j++) b[j].x=rd();
    m+=n;
    n=1;
    while(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].x/n+0.5));
    return 0;
}
FFT

 

posted @ 2018-10-15 16:43  SWHsz  阅读(115)  评论(0编辑  收藏  举报