P3803 [模板] 多项式乘法 (FFT)

Rt

注意len要为2的幂

#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);

inline int read()
{
    char c=getchar();int x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}

int n, m;
struct Complex {
    double x, y;
    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);
    }
};

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]);
        k = len / 2;
        while(j >= k)
        {
            j -= k;
            k /= 2;
        }
        if(j < k) j += k;
    }
}

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;
}

Complex x1[4000005], x2[4000005];

int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 0; i <= n; i++) {
        int u; u = read();
        x1[i] = Complex(1.0 * u, 0);
    }
    for(int i = 0; i <= m; i++) {
        int u; u = read();
        x2[i] = Complex(1.0 * u, 0);
    }

    int len = 1;
    while(len <= n + m) len <<= 1;

    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 <= n + m; i++) printf("%d ", (int)(x1[i].x + 0.5));
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/lwqq3/p/11335961.html
今日推荐