多项式相关算法模板

Posted nineswords

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多项式相关算法模板相关的知识,希望对你有一定的参考价值。

多项式乘法

技术分享图片
 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
", (int)(a[n + m - 2].x + 0.5));
58     return 0;
59 }
FFT

 

以上是关于多项式相关算法模板的主要内容,如果未能解决你的问题,请参考以下文章

[长期更新]模板&算法学习情况

解题报告多项式求值与插值(拉格朗日插值)(ACM / OI)

算法专题多项式相关。

算法专题多项式相关

算法基础课相关代码模板

学习笔记多项式全家桶(包含全套证明)