多项式乘法
1 #include <bits/stdc++.h> 2 using namespace std; 3 const double pi = acos(-1); 4 const int LEN = 1e5 + 5; 5 int n, m, N; 6 namespace ploy { 7 struct comp { 8 double x, y; 9 } a[LEN * 4], b[LEN * 4]; 10 comp operator + (const comp &x,const comp &y) { 11 return (comp){x.x + y.x, x.y + y.y}; 12 } 13 comp operator - (const comp &x,const comp &y) { 14 return (comp){x.x - y.x, x.y - y.y}; 15 } 16 comp operator * (const comp &x,const comp &y) { 17 return (comp){x.x * y.x - x.y * y.y, x.x * y.y + x.y * y.x}; 18 } 19 void FFT(comp *a, int n, int x) { 20 for (int i = n >> 1, j = 1; j < n; j++) { 21 if (i < j) swap(a[i], a[j]); 22 int k = n >> 1; 23 for (; k & i; i ^= k, k >>= 1); 24 i ^= k; 25 } 26 for (int m = 2; m <= n; m <<= 1) { 27 comp w = (comp){cos(2.0 * pi * x / m), sin(2.0 * pi * x / m)}; 28 for (int i = 0; i + m <= n; i += m) { 29 comp t = (comp){1, 0}; 30 for (int j = i; j < i + (m >> 1); j++) { 31 comp u = a[j]; 32 comp v = t * a[j + (m >> 1)]; 33 a[j] = u + v; 34 a[j + (m >> 1)] = u - v; 35 t = t * w; 36 } 37 } 38 } 39 if (x == -1) { 40 for (int i = 0; i < n; i++) a[i].x /= n; 41 } 42 } 43 } 44 using namespace ploy; 45 int main() { 46 scanf("%d %d", &n, &m); 47 n++, m++; 48 N = 1; 49 while (N < n + m - 1) N <<= 1; 50 for (int i = 0; i < n; i++) scanf("%lf", &a[i].x); 51 for (int i = 0; i < m; i++) scanf("%lf", &b[i].x); 52 FFT(a, N, 1); 53 FFT(b, N, 1); 54 for (int i = 0; i < N; i++) a[i] = a[i] * b[i]; 55 FFT(a, N, -1); 56 for (int i = 0; i < n + m - 2; i++) printf("%d ", (int)(a[i].x + 0.5)); 57 printf("%d\n", (int)(a[n + m - 2].x + 0.5)); 58 return 0; 59 }
FFT
原文地址:https://www.cnblogs.com/NineSwords/p/9476698.html
时间: 2024-11-10 23:50:24