[FFT]快速傅里叶变换(分治版)

FFT真好恰!

#include
#include
#include
#include
#include
#include
using namespace std;
#define cp complex
#define ll long long
#define PI acos(-1.0)
#define MAXN 4000010

cp a[MAXN], b[MAXN], c[MAXN];
int n, m, lim;

inline ll read() {
    ll s = 0, w = 1;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
    for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
    return s * w;
}

cp omega(int n, int k) {
    return cp{cos(2 * PI * k / n), sin(2 * PI * k / n)};
}
void fft(cp *a, int n, bool inv) {
    if (n == 1) return;
    static cp buf[MAXN];
    int m = n / 2;
    for (register int i = 0; i < m; i++) {
        buf[i] = a[2 * i];
        buf[i + m] = a[2 * i + 1];
    }
    for (register int i = 0; i < n; i++)
        a[i] = buf[i];
    fft(a, m, inv);
    fft(a + m, m, inv);
    for (register int i = 0; i < m; i++) {
        cp x = omega(n, i);
        if (inv) x = conj(x);
        buf[i] = a[i] + x * a[i + m];
        buf[i + m] = a[i] - x * a[i + m];
    }
    for (register int i = 0; i < n; i++)
        a[i] = buf[i];
}
int main() {
    n = read(), m = read();
    for (register int i = 0; i <= n; i++)
        a[i] = {read(), 0};
    for (register int i = 0; i <= m; i++)
        b[i] = {read(), 0};
    int lim = 1;
    while (lim <= n + m) lim *= 2;
    for (int i = n + 1; i <= lim; i++) a[i] = {0, 0};
    for (int i = m + 1; i <= lim; i++) b[i] = {0, 0};
    fft(a, lim, true), fft(b, lim, true);
    for (register int i = 0; i <= lim; i++)
        c[i] = a[i] * b[i];
    fft(c, lim, false);
    for (register int i = 0; i <= n + m; i++)
        printf("%d ", (int)((c[i].real() / lim) + 0.5));
    return 0;
}

你可能感兴趣的:(学习笔记)