Codeforces 161D 树形DP

题意:给你一颗数,边权值为1,问有多少对节点满足最小距离为k (n <= 50000 , 1 <= k <= 500)


由于k很小,所以我们可以直接对于每个节点保存该节点子树中到它距离为dis(0 <= dis <= k)的点数,对于一个节点,每处理出新一个子树,计算下新子树里的点到已处理的子树里的点满足条件的种数,然后将新子树距离加到已处理的。。


#include 
#include 

struct EDGE {
	int to, next;
}edge[100005];
struct PP {
	int dis[505];
};
int E, head[50005], ans ,K;
void newedge(int u, int to) {
	edge[E].to = to;
	edge[E].next = head[u];
	head[u] = E++;
}
void init() {
	memset(head, -1, sizeof(head));
	E = 0;
	ans = 0;
}
PP dfs(int u, int pre) {
	PP a , b;
	memset(a.dis, 0, sizeof(a.dis));
	if(head[u] == -1) {
		a.dis[0] = 1;
		return a;
	}
	int i, j;
	for(i = head[u];i != -1; i = edge[i].next) {
		int to = edge[i].to;
		if(to == pre)	continue;
		b = dfs(to, u);
		ans += b.dis[K-1];
		for(j = 1;j < K; j++)
			ans += a.dis[j-1]*b.dis[K-j-1];
		for(j = 0;j < K; j++)
			a.dis[j] += b.dis[j];
	}
	for(i = K;i > 0; i--)
		a.dis[i] = a.dis[i-1];
	a.dis[0] = 1;
	return a;
}
int main() {
	int n, a, b, i;
	while(scanf("%d%d", &n, &K) != -1) {
		init();
		for(i = 0;i < n-1; i++) {
			scanf("%d%d", &a, &b);
			newedge(a, b);
			newedge(b, a);
		}
		dfs(1, -1);
		printf("%d\n", ans);
	}
	return 0;
}


你可能感兴趣的:(ACM_Codeforces,ACM_树形DP,树形DP)