标签:
[UOJ#34]多项式乘法
试题描述
这是一道模板题。
给你两个多项式,请输出乘起来后的多项式。
输入
第一行两个整数 n 和 m,分别表示两个多项式的次数。
第二行 n+1 个整数,分别表示第一个多项式的 0 到 n 次项前的系数。
第三行 m+1 个整数,分别表示第一个多项式的 0 到 m 次项前的系数。
输出
输入示例
1 2 1 2 1 2 1
输出示例
1 4 5 2
数据规模及约定
0≤n,m≤105,保证输入中的系数大于等于 0 且小于等于 9。
题解
贴模板。
顺便 FFT 学习链接:Picks的博客
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <set>
using namespace std;
int read() {
int x = 0, f = 1; char c = getchar();
while(!isdigit(c)){ if(c == ‘-‘) f = -1; c = getchar(); }
while(isdigit(c)){ x = x * 10 + c - ‘0‘; c = getchar(); }
return x * f;
}
#define maxn 400010
const double pi = acos(-1.0);
int n, m;
struct Complex {
double a, b;
Complex operator + (const Complex& t) {
Complex ans;
ans.a = a + t.a;
ans.b = b + t.b;
return ans;
}
Complex operator - (const Complex& t) {
Complex ans;
ans.a = a - t.a;
ans.b = b - t.b;
return ans;
}
Complex operator * (const Complex& t) {
Complex ans;
ans.a = a * t.a - b * t.b;
ans.b = a * t.b + b * t.a;
return ans;
}
Complex operator *= (const Complex& t) {
*this = *this * t;
return *this;
}
} a[maxn], b[maxn];
int Ord[maxn];
void FFT(Complex* x, int n, int tp) {
for(int i = 0; i < n; i++) if(i < Ord[i]) swap(x[i], x[Ord[i]]);
for(int i = 1; i < n; i <<= 1) {
Complex wn, w; wn.a = cos(pi / i); wn.b = (double)tp * sin(pi / i);
for(int j = 0; j < n; j += (i << 1)) {
w.a = 1.0; w.b = 0.0;
for(int k = 0; k < i; k++) {
Complex t1 = x[j+k], t2 = w * x[j+k+i];
x[j+k] = t1 + t2;
x[j+k+i] = t1 - t2;
w *= wn;
}
}
}
return ;
}
int main() {
n = read(); m = read();
for(int i = 0; i <= n; i++) a[i].a = (double)read(), a[i].b = 0.0;
for(int i = 0; i <= m; i++) b[i].a = (double)read(), b[i].b = 0.0;
int L = 0;
m += n; for(n = 1; n <= m; n <<= 1) L++;
for(int i = 0; i < n; i++) Ord[i] = (Ord[i>>1] >> 1) | ((i & 1) << L - 1);
FFT(a, n, 1); FFT(b, n, 1);
for(int i = 0; i <= n; i++) a[i] *= b[i];
FFT(a, n, -1);
for(int i = 0; i < m; i++) printf("%d ", (int)(a[i].a / n + .5)); printf("%d\n", (int)(a[m].a / n + .5));
return 0;
}
标签:
原文地址:http://www.cnblogs.com/xiao-ju-ruo-xjr/p/5727919.html