BZOJ2194: 快速傅立叶之二(NTT,卷积)
Submit: 1776 Solved: 1055
[Submit][Status][Discuss]
Description
请计算C[k]=sigma(a[i]*b[i-k]) 其中 k < = i < n ,并且有 n < = 10 ^ 5。 a,b中的元素均为小于等于100的非负整数。
Input
第一行一个整数N,接下来N行,第i+2..i+N-1行,每行两个数,依次表示a[i],b[i] (0 < = i < N)。
Output
输出N行,每行一个整数,第i行输出C[i-1]。
Sample Input
5
3 1
2 4
1 1
2 4
1 4
3 1
2 4
1 1
2 4
1 4
Sample Output
24
12
10
6
1
12
10
6
1
HINT
Source
题目中给的公式不好搞
我们按照套路,将$B$翻转一下
$$C(k) = \sum_0^n a_i * b_{n - 1 - i + k}$$
此时后面的式子就只与$k$有关了
设$$D(n - 1 + k) = \sum_0^n a_i * b_{n - 1 - i + k}$$
直接NTT
#include<cstdio> #define swap(x,y) x ^= y, y ^= x, x ^= y #define LL long long using namespace std; const int MAXN = 3 * 1e5 + 10; inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();} while(c >= '0' && c <= '9') x = x * 10 + c - '0',c = getchar(); return x * f; } const int P = 998244353, g = 3, gi = 332748118; int N; int LL a[MAXN], b[MAXN], r[MAXN]; LL fastpow(LL a, int p, int mod) { LL base = 1; while(p) { if(p & 1) base = (base * a) % mod; a = (a * a) % mod; p >>= 1; } return base % mod; } LL NTT(LL *A, int type, int N, int mod) { for(int i = 0; i < N; i++) if(i < r[i]) swap(A[i], A[r[i]]); for(int mid = 1; mid < N; mid <<= 1) { LL W = fastpow( (type == 1) ? g : gi, (P - 1) / (mid << 1), mod ); for(int j = 0; j < N; j += (mid << 1)) { int w = 1; for(int k = 0; k < mid; k++, w = (w * W) % P) { LL x = A[j + k] % P, y = w * A[j + k + mid] % P; A[j + k] = (x + y) % P; A[j + k + mid] = (x - y + P) % P; } } } if(type == -1) { LL inv = fastpow(N, mod - 2, mod); for(int i = 0; i < N; i++) A[i] = (A[i] * inv) % mod; } } int main() { #ifdef WIN32 freopen("a.in","r",stdin); #endif N = read(); for(int i = 0; i < N; i++) a[i] = read(), b[N - i] = read(); int limit = 1, L = 0; while(limit <= N + N) limit <<=1, L++; for(int i = 0; i < limit; i++) r[i] = (r[i >> 1] >> 1) | ((i & 1) << (L - 1)); NTT(a, 1, limit, P); NTT(b, 1, limit, P); for(int i = 0; i < limit; i++) a[i] = (a[i] * b[i]) % P; NTT(a, -1, limit, P); for(int i = 0; i < N * 2; i++) printf("%d\n",a[i] % P); return 0; }
作者:自为风月马前卒
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。