1. 程式人生 > >洛谷OJ P3803 【模板】多項式乘法(FFT)

洛谷OJ P3803 【模板】多項式乘法(FFT)

題目思路:FFT模板題

AC程式碼:

// luogu-judger-enable-o2
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;

const double PI = acos(-1.0);
//複數結構體
struct Complex{
    double x,y;   //實部和虛部, x+yi
    Complex(double _x=0.0,double _y=0.0){
        x=_x,y=_y;
    }
    Complex operator - (const Complex &b)const{
        return Complex(x-b.x,y-b.y);
    }
    Complex operator + (const Complex &b)const{
        return Complex(x+b.x,y+b.y);
    }
    Complex operator * (const Complex &b)const{
        return Complex(x*b.x-y*b.y,x*b.y+y*b.x);
    }
};

/*
 * 進行FFT和IFFT前的反轉變換。
 * 位置i和 (i二進位制反轉後位置)互換
 * len必須去2的冪
 */
void change(Complex y[],int len)
{
    int i,j,k;
    for(i = 1, j = len/2;i < len-1; i++)
    {
        if(i < j)swap(y[i],y[j]);
        //交換互為小標反轉的元素,i<j保證交換一次
        //i做正常的+1,j左反轉型別的+1,始終保持i和j是反轉的
        k = len/2;
        while( j >= k)
        {
            j -= k;
            k /= 2;
        }
        if(j < k) j += k;
    }
}
/*
 * 做FFT
 * len必須為2^k形式,
 * on==1時是DFT,on==-1時是IDFT
 */
void fft(Complex y[],int len,int on)
{
    change(y,len);
    for(int h = 2; h <= len; h <<= 1)
    {
        Complex wn(cos(-on*2*PI/h),sin(-on*2*PI/h));
        for(int j = 0;j < len;j+=h)
        {
            Complex w(1,0);
            for(int k = j;k < j+h/2;k++)
            {
                Complex u = y[k];
                Complex t = w*y[k+h/2];
                y[k] = u+t;
                y[k+h/2] = u-t;
                w = w*wn;
            }
        }
    }
    if(on == -1)
        for(int i = 0;i < len;i++)
            y[i].x /= len;
}
const int MAXN = 4000010;
Complex x1[MAXN],x2[MAXN];
char str1[MAXN/2],str2[MAXN/2];
int sum[MAXN];
int main()
{
    int n,m,x;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int len = 1;
        while(len < n*2 || len < m*2)len<<=1;

        for(int i = 0;i < n+1;i++){
            scanf("%d",&x);
            x1[i] = Complex(x,0);
        }
        for(int i = n+1;i < len;i++)
            x1[i] = Complex(0,0);

        for(int i = 0;i < m+1;i++){
            scanf("%d",&x);
            x2[i] = Complex(x,0);
        }
        for(int i = m+1;i < len;i++)
            x2[i] = Complex(0,0);
        //求DFT
        fft(x1,len,1);
        fft(x2,len,1);
        for(int i = 0;i < len;i++)
            x1[i] = x1[i]*x2[i];
        fft(x1,len,-1);
        for(int i = 0;i < len;i++)
            sum[i] = (int)(x1[i].x+0.5);
        for(int i=0;i<n+m+1;i++)
            printf("%d%c",sum[i],(i==n+m)?'\n':' ');
    }
    return 0;
}