之前写过一个vector的多项式汇总。。。不过常数特别大
最近事儿比较少,准备写一个int[]的
目前没写完,先打了发多项式求逆,蛙了好几发。。。
最后发现递归下去回来之后忘了清系数了。。。
int[]版的主要是数组大小和高位系数比较恶心,还有数组清空啥的。。。
不过常数肯定比vector小很多,所以还是尝试写一下好了
#include <cstdio>
#include <algorithm>
using namespace std;
const int p = 998244353;
int qpow(int x, int y)
{
int res = 1;
while (y > 0)
{
if (y & 1) res = res * (long long)x % p;
x = x * (long long)x % p, y >>= 1;
}
return res;
}
void ntt(int *a, int len, int flag)
{
int *r = new int[len];
r[0] = 0;
for (int i = 1; i < len; i++) r[i] = (r[i >> 1] >> 1) | ((i & 1) * (len >> 1));
for (int i = 0; i < len; i++) if (i < r[i]) swap(a[i], a[r[i]]);
for (int i = 1; i < len; i <<= 1)
{
int g1 = qpow(3, (p - 1) / (i * 2));
for (int j = 0; j < len; j += i << 1)
for (int g = 1, k = 0; k < i; k++, g = g * (long long)g1 % p)
{
int t = a[j + i + k] * (long long)g % p;
a[j + i + k] = ((a[j + k] - t) % p + p) % p;
a[j + k] = (a[j + k] + t) % p;
}
}
if (flag == -1)
{
reverse(a + 1, a + len);
for (int i = 0, inv = qpow(len, p - 2); i < len; i++) a[i] = a[i] * (long long)inv % p;
}
delete []r;
}
void poly_inv(int *a, int len)
{
if (len == 1) { a[0] = qpow(a[0], p - 2); return; }
int len1 = len / 2;
int *f0 = new int[len * 2];
for (int i = 0; i < len1; i++) f0[i] = a[i];
for (int i = len1; i < len * 2; i++) f0[i] = 0;
poly_inv(f0, len1);
for (int i = len1; i < len * 2; i++) f0[i] = 0;
ntt(f0, len * 2, 1), ntt(a, len * 2, 1);
for (int i = 0; i < len * 2; i++) a[i] = ((2 * f0[i] % p - a[i] * (long long)f0[i] % p * f0[i] % p) % p + p) % p;
ntt(a, len * 2, -1);
delete []f0;
}
int a[500000], n, len = 1;
int main()
{
scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]);
while (len < n) len *= 2;
poly_inv(a, len);
for (int i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}
原文地址:https://www.cnblogs.com/oier/p/10289877.html
时间: 2024-11-08 22:42:32