H. Path Counting
time limit per test
5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a rooted tree. Let's denote d(x) as depth of node x: depth of the root is 1, depth of any other node x is d(y) + 1, where y is a parent of x.
The tree has the following property: every node x with d(x) = i has exactly ai children. Maximum possible depth of a node is n, and an = 0.
We define fk as the number of unordered pairs of vertices in the tree such that the number of edges on the simple path between them is equal to k.
Calculate fk modulo 109 + 7 for every 1 ≤ k ≤ 2n - 2.
Input
The first line of input contains an integer n (2 ≤ n ≤ 5 000) — the maximum depth of a node.
The second line of input contains n - 1 integers a1, a2, ..., an - 1 (2 ≤ ai ≤ 109), where ai is the number of children of every node x such that d(x) = i. Since an = 0, it is not given in the input.
Output
Print 2n - 2 numbers. The k-th of these numbers must be equal to fk modulo 109 + 7.
Examples
input
Copy
4
2 2 2
output
Copy
14 19 20 20 16 16
input
Copy
3
2 3
output
Copy
8 13 6 9
Note
This the tree from the first sample:
题意:一棵深度为n的树,深度为i的节点有a[i]个儿子,问树上有多少条长度为x的链,x∈[1,k]
题解:首先很容易想到用DP做
设f[i][j]为以深度为i的点为端点,往下走j步的方案数,pre[i]表示深度为i的节点的个数,dp[i][j]表示以i为LCA长度为j的链的个数
然后很容易想到一个DP方程:
右边用可取模的FFT转移一下就行了。。。原本是这么想的。。。然而O(n^2logn)过不了。。。
转换一下思路:设dp[i][j][k]为以i为端点,向上走k步,长度为j的链的个数
可以得到:
发现第三维可以用前缀和优化,得到dp[i][j]:以i为端点,向上至少走一步,长度为j的链的个数
时间复杂度为O(n^2)
然后这道题很苟地卡空间,所以dp数组和f数组需要重用一下,因此j需要从大到小枚举
#include<bits/stdc++.h>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define x first
#define y second
#define rep(i,a,b) for(int i=a;i<(b);++i)
#define per(i,a,b) for(int i=a-1;i>=(b);--i)
#define fuck(x) cout<<'['<<#x<<' '<<(x)<<']'
#define clr(a,b) memset(a,b,sizeof(a))
#define eps 1e-10
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> VI;
typedef pair<int, int> pii;
typedef unsigned int ui;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
const int mod = 1e9 + 7;
const int N = 5e3 + 5;
int inv2 = (mod + 1) / 2;
int a[N], f[N][N << 1], pre[N], ans[N << 1];
ll mul(ll x, ll y) {return x * y % mod;}
int main() {
#ifdef local
freopen("in.txt", "r", stdin);
#endif // local
int n; cin >> n;
rep(i, 1, n) cin >> a[i];
pre[0] = 1; rep(i, 1, n) pre[i] = (ll)pre[i - 1] * a[i] % mod;
rep(i, 1, n + 1) f[i][0] = 1;
per(i, n, 1) rep(j, 1, n - i + 1) {
f[i][j] = (ll)a[i] * f[i + 1][j - 1] % mod;
ans[j] = (ans[j] + (ll) pre[i - 1] * f[i][j]) % mod;
}
rep(i, 1, n + 1) per(j, 2 * n - 1, 1) {
f[i][j] = f[i - 1][j - 1];
if(j > 1 && i > 1) f[i][j] = (f[i][j] + mul(f[i][j - 2], a[i - 1] - 1)) % mod;
ans[j] = (ans[j] + (ll) f[i][j] * pre[i - 1]) % mod;
}
rep(i, 1, 2 * n - 1) printf("%lld%c", (ll)ans[i] * inv2 % mod, i == 2 * n - 2 ? '\n' : ' ');
return 0;
}