Educational Codeforces Round 40 H. Path Counting DP

本文介绍了一种在给定树形结构中计算特定长度有序点对数量的算法,通过动态规划方法,实现对每一层节点进行有效计算,最终得到所有可能的有序点对个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
给你一棵树,第i层每一个节点都有a[i-1]个子节点。
让你求对于每一个k,长度为k的有序点对个数。


Sample Input
4
2 2 2


Sample Output
14 19 20 20 16 16


设f[i][j][k]为到第i层,长度为j的有序点对。
k=0时表示有一个端点处于这层,k=1时表示有两个端点处于这层的方案数。
直接转移即可。


#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
const LL mod = 1e9 + 7;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

LL f[2][2][10010], ans[10010], a[5100];

int main() {
	int n = read();
	for(int i = 2; i <= n; i++) a[i] = read();
	f[0][0][0] = 1;
	int now = 0;
	for(int i = 2; i <= n; i++) {
		now ^= 1; memset(f[now], 0, sizeof(f[now]));
		f[now][0][0] = f[now ^ 1][0][0] * a[i] % mod;
		f[now][0][1] = f[now][0][0];
		f[now][1][2] = f[1 ^ now][0][0] * ((a[i] * (a[i] - 1) / 2) % mod) % mod;
		for(int j = 4; j <= 2 * i - 2; j++) f[now][1][j] = (f[1 ^ now][1][j - 2] * a[i] % mod) * a[i] % mod;
		for(int j = 2; j < 2 * i - 2; j++) {
			f[now][0][j] = f[1 ^ now][0][j - 1] * a[i] % mod;
			if(j % 2 == 1) (f[now][0][j] += (f[1 ^ now][1][j - 1] * 2LL % mod) * a[i] % mod) %= mod;
		}
		for(int j = 1; j <= 2 * i - 2; j++) {
			(ans[j] += f[now][0][j]) %= mod;
			if(j % 2 == 0) (ans[j] += f[now][1][j]) %= mod;
		}
	} for(int i = 1; i <= 2 * n - 2; i++) printf("%lld ", ans[i]);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值