跳到正文

个人记录

P3803 【模板】多项式乘法(FFT)

yqzx0307约 5 分钟
原文

这是 2026年6月29日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本
C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
constexpr int maxn=1e7+10;
constexpr double pi=acos(-1.0);
constexpr double eps=1e-6;
int n,m;
int Fx[maxn],Gx[maxn];

typedef struct comp
{
    double Re,Im;
    comp()=default;
    comp(int a)
    {
        this->Re=a;
        this->Im=0;
    }
    comp(double x,double y)
    {
        this->Re=x;
        this->Im=y;
    }
    comp operator+(const comp& z)
    {
        return comp(Re+z.Re,Im+z.Im);
    }
    comp operator-(const comp& z)
    {
        return comp(Re-z.Re,Im-z.Im);
    }
    comp operator*(const comp& z)
    {
        return comp(Re*z.Re-Im*z.Im,Re*z.Im+Im*z.Re);
    }
    comp operator/(const int& r)
    {
        double R=r;
        return comp(Re/R,Im/R);
    }

    void operator*=(const comp& z)
    {
        (*this)=(*this)*z;
    }
    void operator/=(const int& r)
    {
        double R=r;
        (*this)=(*this)/R;
    }
}comp;//复数结构体

void prt(comp &z)
{
    printf("%.3lf %.3lf\n",z.Re,z.Im);
}//调试函数

comp tmp[maxn];
void DFT(comp *f,int n,int rev=1)
{
    if(n==1)
    {
        return ;
    }
    int half_n=(n>>1);
    for(int i=0;i<n;++i)
    {
        tmp[i]=f[i];
    }//准备奇偶重排

    for(int i=0;i<half_n;++i)
    {
        f[i]=tmp[i<<1];
        f[i+half_n]=tmp[i<<1|1];
    }//项数分离
    comp *F=f;
    comp *G=f+half_n;
    DFT(F,half_n,rev);//A[0]
    DFT(G,half_n,rev);//A[1]

    //开始拼接计算
    comp w_1=comp(cos(2*pi/n),rev*sin(2*pi/n));//单位根$w_n^1$
    comp w_k=comp(1,0);//$w_n^k$
    for(int i=0;i<half_n;++i)
    {
        tmp[i]=F[i]+w_k*G[i];//k<half_n
        tmp[i+half_n]=F[i]-w_k*G[i];//k>=half_n

        w_k*=w_1;
    }

    for(int i=0;i<n;++i)
    {
        f[i]=tmp[i];
    }
}

void IDFT(comp *f,int n)
{
    DFT(f,n,-1);
    for(int i=0;i<n;++i)
    {
        f[i]/=n;
    }
}

comp F_[maxn],G_[maxn];
void mul()
{
    for(int i=0;i<=n;++i)
    {
        F_[i]=comp(Fx[i]);
    }
    for(int i=0;i<=m;++i)
    {
        G_[i]=comp(Gx[i]);
    }

    int h_len=(1<<(__lg(n+m+1)+1));
    for(int i=n+1;i<h_len;++i)
    {
        F_[i]=comp(0);
    }
    for(int i=m+1;i<h_len;++i)
    {
        G_[i]=comp(0);
    }

    DFT(F_,h_len,1);
    DFT(G_,h_len,1);

    for(int i=0;i<h_len;++i)
    {
        F_[i]*=G_[i];//存入结果点值表达
    }
    IDFT(F_,h_len);//rev有初始值,可不加

    for(int i=0;i<h_len;++i)
    {
        Fx[i]=F_[i].Re+0.5;
    }
    for(int i=0;i<=n+m;++i)
    {
        printf("%lld ",Fx[i]);
    }
}
signed main()
{
    scanf("%lld%lld",&n,&m);
    for(int i=0;i<=n;++i)
    {
        scanf("%lld",Fx+i);
    }
    for(int i=0;i<=m;++i)
    {
        scanf("%lld",Gx+i);
    }
    mul();
    return 0;
}

https://www.luogu.com.cn/problem/P3803