(同步个人博客 http://sxysxy.org/blogs/16 到csdn)
多项式乘法 http://uoj.ac/problem/34
之前用FFT交了一个无限WA,怀疑是精度有问题然后就转向NTT。
关于FFT和NTT力荐这两篇吼文章,讲得太吼了!
http://blog.csdn.net/acdreamers/article/details/39026505
http://blog.miskcoo.com/2015/04/polynomial-multiplication-and-fast-fourier-transform#i-15
塔萌讲得很好了,我就存个这个模板。
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <list>
#include <cmath>
#include <queue>
#include <vector>
#include <deque>
#include <cstring>
#include <string>
using namespace std;
typedef long long LL;
const int MAXN = 1 << 18;
//const int MAXM = (int)(log(MAXN))+3; //够用即可
const int MAXM = 23;
const int MOD = (479<<21)+1; //即质数 1004535809
const int G = 3; //G^k(k=0,1...MOD-2)%MOD的值互不相同
/*
关于NTT的模数,这里写两个
模数 (479<<21)+1 = 1004535809 原根G = 3,MAXN可以开到1<<21
模数 998244353 (UOJ模数) 原根G = 3, MAXN可以开到1<<23
*/
LL quick_pow(LL a, LL b)
{
LL res = 1;
LL base = a%MOD;
while(b)
{
if(b & 1)
{
res *= base;
res %= MOD;
}
b >>= 1;
base *= base;
base %= MOD;
}
return res;
}
LL omg[MAXM+1];
void calcOmg()
{
for(int i = 0; i <= MAXM; i++)
{
int k = 1 << i;
omg[i] = quick_pow(G, (MOD-1)/k);
}
}
class NTTer
{
public:
LL a[MAXN];
LL len;
void trans()
{
int j = len >> 1;
for(int i = 1; i < len-1; i++)
{
if(i < j)swap(a[i], a[j]);
int k = len >> 1;
while(j >= k)
{
j -= k;
k >>= 1;
}
if(j < k)j += k;
}
}
void NTT(bool DNTT = false)
{
trans();
int id = 0;
for(int h = 2; h <= len; h <<= 1)
{
id++;
for(int j = 0; j < len; j += h)
{
LL omgn = 1;
for(int k = j; k < j + h/2; k++)
{
LL u = a[k] % MOD;
LL t = omgn * a[k + h/2] % MOD;
a[k] = (u+t)%MOD;
a[k+h/2] = (u-t+MOD)%MOD;
omgn = omgn*omg[id]%MOD;
}
}
}
if(DNTT)
{
for(int i = 1; i < len/2; i++)
swap(a[i], a[len-i]);
LL inv = quick_pow(len, MOD-2);
for(int i = 0; i < len; i++)
a[i] = a[i] * inv % MOD;
}
}
void mul(NTTer &o)
{
int s = 1;
while(s < len+o.len) s<<=1;
len = o.len = s;
NTT(false);
o.NTT(false);
for(int i = 0; i < len; i++)
a[i] = a[i]*o.a[i]%MOD;
NTT(true);
}
};
NTTer x, y;
int main()
{
calcOmg();
int n, m;
scanf("%d %d", &n, &m);
for(int i = 0; i <= n; i++)
scanf("%lld", &x.a[i]);
x.len = n+1;
for(int i = 0; i <= m; i++)
scanf("%lld", &y.a[i]);
y.len = m+1;
x.mul(y);
for(int j = 0; j < n+m+1; j++)
printf("%lld ", x.a[j]);
return 0;
}