NTT快速数论变换 模板

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define md 998244353
#define N 4000010
#define ll long long
ll a[N], b[N];
int ns, p, rev[N];
ll ksm(ll x, ll y) {
	if(!y) return 1;
	ll l = ksm(x, y / 2);
	if(y % 2) return l * l % md * x % md;
	return l * l % md;
}
void ntt(ll *a, int r) {
	for(int i = 0; i < ns; i++) if(i < rev[i]) swap(a[i], a[rev[i]]);
	for(int i = 2; i <= ns; i *= 2) {
		ll t = ksm(3, (md - 1) / i);
		if(r == -1) t = ksm(t, md - 2);
		for(int j = 0; j < ns; j += i) {
			ll s = 1;
			for(int k = 0; k < i / 2; k++) {
				ll A = a[j + k], B = a[j + i / 2 + k] * s % md;
				a[j + k] = (A + B) % md;
				a[j + i / 2 + k] = (A - B + md) % md;
				s = s * t % md;
			}
		}
	}
	if(r == -1) {
		ll t = ksm(ns, md - 2);
		for(int i = 0; i < ns; i++) a[i] = a[i] * t % md;
	}
}
ll read() {
	int s = 0;
	char x = getchar();
	while(x < '0' || x > '9') x = getchar();
	while(x >= '0' && x <= '9') s = s * 10 + x - 48, x = getchar();
	return s;
}
int main() {
	int n, m, i;
	scanf("%d%d", &n, &m);
	for(i = 0; i <= n; i++) a[i] = read();
	for(i = 0; i <= m; i++) b[i] = read();
	ns = 1, p = 0;
	while(ns <= n + m) ns = ns * 2, p++;
	rev[0] = 0;
	for(i = 0; i < ns; i++) {
		rev[i] = rev[i / 2] / 2 + (i % 2) * ns / 2;
	}
	ntt(a, 1);
	ntt(b, 1);
	for(i = 0; i < ns; i++) a[i] = a[i] * b[i] % md;
	ntt(a, -1);
	for(i = 0; i <= n + m; i++) printf("%lld ", a[i]);
	return 0;
}
posted @ 2021-04-06 10:41  AnAn_119  阅读(58)  评论(0编辑  收藏  举报