FFT总结

时间:2022-02-05 01:40:37

讲真的,FFT我只会背板子。其他就只能抓瞎了。
【模板】FFT

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<complex>
using namespace std;
const int N = 3000005;
const double Pi = acos(-1);
int gi()
{
    int x=0,w=1;char ch=getchar();
    while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if (ch=='-') w=0,ch=getchar();
    while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return w?x:-x;
}
int n,m,r[N],l;
complex<double>a[N],b[N];
void FFT(complex<double>*P,int opt)
{
    for (int i=1;i<n;i++)
        if (i<r[i]) swap(P[i],P[r[i]]);
    for (int i=1;i<n;i<<=1)
    {
        complex<double>W(cos(Pi/i),opt*sin(Pi/i));
        for (int p=i<<1,j=0;j<n;j+=p)
        {
            complex<double>w(1,0);
            for (int k=0;k<i;k++,w*=W)
            {
                complex<double>X=P[j+k],Y=w*P[j+k+i];
                P[j+k]=X+Y;P[j+k+i]=X-Y;
            }
        }
    }
}
int main()
{
    n=gi();m=gi();
    for (int i=0;i<=n;i++) a[i]=gi();
    for (int i=0;i<=m;i++) b[i]=gi();
    m+=n;
    for (n=1;n<=m;n<<=1) ++l;--l;
    for (int i=0;i<n;i++) r[i]=(r[i>>1]>>1)|((i&1)<<l);
    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].real()/n+0.5));
    return 0;
}