本文主要是介绍分治NTT(洛谷P4721),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目路径:P4721 【模板】分治 FFT - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
思路:
如果用NTT一个一个求时间复杂度是O(n^2)。
可以发现,i<j,f[i]会对f[j]有贡献,而f[j]对f[i]没有贡献,考虑分治。
对于区间(l,r),当我们算出f[l]-f[mid](mid=(l+r)>>1),我们可以算出(l,mid)对后边区间贡献,再算(mid+1,r)内的f值。
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
using namespace std;
#define LL long long
const int N = 4e5 + 10;
const LL mod = 998244353;
const double PI = acos(-1);
LL a[N], b[N], f[N], g[N];
int n,tot,bit;
int rel[N];
LL gi,gg=3;
LL quick(LL a, LL b, LL mod)
{
LL ans = 1;
while (b)
{
if (b & 1) ans = ans * a % mod;
b = b >> 1;
a = a * a % mod;
}
return ans;
}
void ntt(LL a[], int op)
{
for (int i = 0; i < tot; i++)
if (i < rel[i]) swap(a[i], a[rel[i]]);
for (int m = 2; m<= tot; m=m<<1)
{
LL g1 = quick((op == 1) ? gg : gi, (mod - 1) / m,mod);
for (int i = 0; i < tot; i += m)
{
LL gk = 1;
for (int j = 0; j < m / 2; j++)
{
LL x = a[i + j], y = a[i + j + m / 2]*gk%mod;
a[i + j] = (x + y) % mod;
a[i + j + m / 2] = (x - y + mod) % mod;
gk = gk * g1 % mod;
}
}
}
}
void cbd(int l,int r)
{
if (l == r) return;
int mid = (l + r) >> 1;
cbd(l, mid);
tot = 1;
bit = 0;
while (tot <= (mid - l) + (r - l)) {
tot <<= 1;
++bit;
}
for (int i = 0; i < tot; i++) a[i] = b[i] = 0;
for (int i = l; i <= mid; i++) a[i-l] = f[i];
for (int i = 0; i <= r - l; i++) b[i] = g[i];
for (int i = 0; i < (1 << bit); ++i)
{
rel[i] = (rel[i >> 1] >> 1) | ((i & 1) << (bit - 1));
}
ntt(a, 1);
ntt(b, 1);
for (int i = 0; i < tot; i++) a[i] = a[i] * b[i];
ntt(a, -1);
LL gk = quick(tot, mod - 2, mod);
for (int i = 0; i < tot; i++)
a[i] = (a[i] * gk % mod + mod) % mod;
for (int i = mid + 1; i <= r; i++) f[i] = (f[i] + a[i - l]) % mod;
cbd(mid + 1, r);
}
int main() {
cin >> n;
for (int i = 1; i < n; i++) cin >> g[i];
gi = quick(gg, mod - 2, mod);
f[0] = 1;
cbd(0,n-1);
for (int i = 0; i < n; i++) cout << f[i] << " ";
cout << endl;
return 0;
}
这篇关于分治NTT(洛谷P4721)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!