NTT 没过样例求助
查看原帖
NTT 没过样例求助
366516
xuyiyang楼主2023/11/16 16:45
#include <bits/stdc++.h>

using namespace std;

const int N = 4000010, P = 998244353, Inv = 332748118;
typedef long long LL;

int a[N], b[N];
int n, m, k;
int r[N];

int qmi(int a, int b, int p)
{
	int res = 1;
	while (b)
	{
		if (b & 1) res = (LL)res * a % p;
		b >>= 1; a = (LL)a * a % p;
	}
	return res;
} 

int log_2(int x)
{
	int res = 0;
	if (x & 0xffff0000) res += 16, x >>= 16;
	if (x & 0xff00) res += 8, x >>= 8;
	if (x & 0xf0) res += 4, x >>= 4;
	if (x & 0xc) res += 2; x >>= 2;
	if (x & 2) res ++ ;
	return res; 
}

void NTT(int a[], int f)
{
	for (int i = 0; i < k; i ++ ) if (i < r[i]) swap(a[i], a[r[i]]);
	int t, w, x, y;
	for (int len = 2; len <= k; len <<= 1)
	{
		t = qmi(f ? 3 : Inv, (P - 1) / len, P);
		for (int l = 0; l < k; l += len)
		{
			int r = l + len - 1; w = 1;
			for (int i = 0, j = len >> 1; j < len; i ++ , j ++ , w = (LL)w * t % P)
			{
				int x = a[l + i], y = (LL)w * a[l + j] % P;
				a[l + i] = (x + y) % P, a[l + j] = (x - y + P) % P;
			}
		}
	}
}

int main()
{
	scanf("%d%d", &n, &m);
	for (int i = 0; i <= n; i ++ ) scanf("%d", &a[i]);
	for (int i = 0; i <= m; i ++ ) scanf("%d", &b[i]);
	int bit = log_2(n + m); k = 1 << bit + 1;
	for (int i = 0; i < k; i ++ ) r[i] = r[i >> 1] >> 1 | (i & 1) << bit;
	NTT(a, 1), NTT(b, 1);
	for (int i = 0; i < k; i ++ ) a[i] = (LL)a[i] * b[i] % P;
	NTT(a, 0);
	
	for (int i = 0; i <= n + m; i ++ ) printf("%lld ", (LL)a[i] * qmi(k, P - 2, P) % P); 
	return 0;
}

2023/11/16 16:45
加载中...