FFT
看这两篇博客就差不多了
第一篇:链接
第二篇:链接
关于虚数:链接
以上来自:Candy?
这篇里面也有一些链接可以看看: 点我
拖了好久...
这里就放个抄来的模板吧=_=
1 const int maxn = 200010; 2 const double pi = acos(-1.0); 3 complex<double> omega[maxn], inverse[maxn]; 4 5 void init(int n){ 6 for(int i = 0; i < n; i++){ 7 omega[i] = complex<double>(cos(2 * pi / n * i), sin(2 * pi / n * i)); 8 inverse[i] = conj(omega[i]); 9 } 10 } 11 void transform(complex<double> *a, int n, complex<double> *omega){ 12 int k = 0; 13 while((1 << k) < n) k++; 14 for(int i = 0; i < n; i++){ 15 int t = 0; 16 for(int j = 0; j < k; j++) if(i & (1 << j)) t |= (1 << (k - j - 1)); 17 if(i < t) swap(a[i], a[t]); 18 } 19 for(int l = 2; l <= n; l *= 2){ 20 int m = l / 2; 21 for(complex<double> *p = a; p != a + n; p += l){ 22 for(int i = 0; i < m; i++){ 23 complex<double> t = omega[n / l * i] * p[m + i]; 24 p[m + i] = p[i] - t; 25 p[i] += t; 26 } 27 } 28 } 29 } 30 void dft(complex<double> *a, int n){ 31 transform(a, n, omega); 32 } 33 void idft(complex<double> *a, int n){ 34 transform(a, n, inverse); 35 for(int i = 0; i < n; i++) a[i] /= n; 36 } 37 38 void mul(int *a, int n1, int *b, int n2, int *res){ 39 int n = 1; 40 while(n < n1 + n2) n <<= 1; 41 complex<double> c1[maxn], c2[maxn]; 42 for(int i = 0; i < n1; i++) c1[i].real(a[i]); 43 for(int i = 0; i < n2; i++) c2[i].real(b[i]); 44 init(n); 45 dft(c1, n); dft(c2, n); 46 for(int i = 0; i < n; i++) c1[i] *= c2[i]; 47 idft(c1, n); 48 for(int i = 0; i < n1 + n2 - 1; i++) res[i] = (int)(c1[i].real() + 0.5); 49 }