洛谷 - P3803 - 【模板】多项式乘法(FFT) - FFT
https://www.luogu.org/problemnew/show/P3803
用反向学习的FFT通过这个东西。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 3e5;
const double PI = acos(-1.0);
struct Complex {
double x, y;
Complex() {}
Complex(double x, double y): x(x), y(y) {}
friend Complex operator+(const Complex &a, const Complex &b) {
return Complex(a.x + b.x, a.y + b.y);
}
friend Complex operator-(const Complex &a, const Complex &b) {
return Complex(a.x - b.x, a.y - b.y);
}
friend Complex operator*(const Complex &a, const Complex &b) {
return Complex(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}
} A[MAXN + 5], B[MAXN + 5];
void FFT(Complex a[], int n, int op) {
for(int i = 1, j = n >> 1; i < n - 1; ++i) {
if(i < j)
swap(a[i], a[j]);
int k = n >> 1;
while(k <= j) {
j -= k;
k >>= 1;
}
j += k;
}
for(int len = 2; len <= n; len <<= 1) {
Complex wn(cos(2.0 * PI / len), sin(2.0 * PI / len)*op);
for(int i = 0; i < n; i += len) {
Complex w(1.0, 0.0);
for(int j = i; j < i + (len >> 1); ++j) {
Complex u = a[j], t = a[j + (len >> 1)] * w ;
a[j] = u + t, a[j + (len >> 1)] = u - t;
w = w * wn;
}
}
}
if(op == -1) {
for(int i = 0; i < n; ++i)
a[i].x = (int)(a[i].x / n + 0.5);
}
}
int pow2(int x) {
int res = 1;
while(res < x)
res <<= 1;
return res;
}
void convolution(Complex A[], Complex B[], int Asize, int Bsize) {
int n = pow2(Asize + Bsize - 1);
for(int i = 0; i < n; ++i) {
A[i].y = 0.0;
B[i].y = 0.0;
}
for(int i = Asize; i < n; ++i)
A[i].x = 0;
for(int i = Bsize; i < n; ++i)
B[i].x = 0;
FFT(A, n, 1);
FFT(B, n, 1);
for(int i = 0; i < n; ++i)
A[i] = A[i] * B[i];
FFT(A, n, -1);
return;
}
int C[MAXN + 5];
int carry(int n) {
for(int i = 0; i < n; i++) {
C[i] = A[i].x;
}
for(int i = 0; i < n; i++) {
C[i + 1] += C[i] / 10;
C[i] %= 10;
}
while(C[n]) {
C[n + 1] += C[n] / 10;
C[n] %= 10;
n++;
}
while(n && !C[n - 1]) {
n--;
}
return n;
}
int main() {
#ifdef Yinku
freopen("Yinku.in", "r", stdin);
#endif // Yinku
int n;
scanf("%d", &n);
for(int i = n-1; i >=0; --i) {
int tmp;
scanf("%1d", &tmp);
A[i].x = tmp;
}
for(int i = n-1; i >=0; --i) {
int tmp;
scanf("%1d", &tmp);
B[i].x = tmp;
}
convolution(A, B, n, n);
n = carry(pow2(n + n - 1));
if(n == 0) {
printf("0\n");
} else {
for(int i = n - 1; i >= 0; --i) {
printf("%d", C[i]);
}
printf("\n");
}
return 0;
}