[模板] fft模板

省选前复习。这是一个普通的 fft 模板。
(发现自己差点fft模板不会打了)

因为没有预处理&&用了complex类可能常数比较大。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

#include <cstring>
#include <cstdio>
#include <algorithm>
#include <complex>
#include <cmath>

using namespace std;

typedef complex<double> C;

const int maxn = 100010;

int n, m;
int rev[maxn*4];
C c_a[maxn*4], c_b[maxn*4], c_c[maxn*4];
int a[maxn], b[maxn];

void (C *a, int len, int t) {
rev[0] = 0;
int x = 0; while ((1<<x) < len) ++ x;
for (int i = 1; i < len; i++) {
rev[i] = (rev[i>>1]>>1);
if (i & 1) rev[i] |= (1<<(x-1));
}
for (int i = 0; i < len; i++)
if (rev[i] > i)
swap(a[rev[i]], a[i]);
for (int l = 2; l <= len; l <<= 1) {
C wn(cos(2*M_PI/l), t*sin(2*M_PI/l));
for (int s = 0; s < len; s += l) {
C w(1, 0);
for (int i = s; i < (s+(l>>1)); i++) {
C v1 = a[i], v2 = a[i+(l>>1)]*w;
a[i] = v1+v2;
a[i+(l>>1)] = v1-v2;
w = w * wn;
}
}
}
if (t == -1) {
for (int i = 0; i < len; i++) {
a[i] /= len;
}
}
}

int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 0; i <= m; i++)
scanf("%d", &b[i]);
int l = 1;
while (l < n+m+1) l <<= 1;
for (int i = 0; i <= n; i++) c_a[i] = a[i];
for (int i = 0; i <= m; i++) c_b[i] = b[i];
fft(c_a, l, 1); fft(c_b, l, 1);
for (int i = 0; i < l; i++)
c_c[i] = c_a[i]*c_b[i];
fft(c_c, l, -1);
for (int i = 0; i <= n+m; i++) {
printf("%d ", int(c_c[i].real()+0.5));
}
printf("n");
return 0;
}