Codeforces 161D 树形DP
2013-07-18 16:43
134 查看
题意:给你一颗数,边权值为1,问有多少对节点满足最小距离为k (n <= 50000 , 1 <= k <= 500)
由于k很小,所以我们可以直接对于每个节点保存该节点子树中到它距离为dis(0 <= dis <= k)的点数,对于一个节点,每处理出新一个子树,计算下新子树里的点到已处理的子树里的点满足条件的种数,然后将新子树距离加到已处理的。。
#include <stdio.h>
#include <string.h>
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;
}
由于k很小,所以我们可以直接对于每个节点保存该节点子树中到它距离为dis(0 <= dis <= k)的点数,对于一个节点,每处理出新一个子树,计算下新子树里的点到已处理的子树里的点满足条件的种数,然后将新子树距离加到已处理的。。
#include <stdio.h>
#include <string.h>
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;
}
相关文章推荐
- HDOJ 1011 树形DP
- HDU 2196 树形DP
- HDU---1561-The more, The Better (树形DP)
- POJ 1947树形DP
- HDU 1561 The more, The Better (树形DP)
- HDU 1561 The more, The Better(树形DP)
- 树形DP
- [luogu1272]重建道路(树形dp)
- ZOJ 1134 Strategic Game(树形DP)
- Uva 6436 - The Busiest City 树形DP
- 树形dp-hdu1561
- hdu 4003 Find Metal Mineral K个机器人从S出发遍历树上所有点的经过的最小权值 树形DP
- HDU Computer (树形DP)
- lightoj 1252 - Maintaining Communities 树形DP
- hdu1011(树形dp)
- hdu1561(树形dp)
- hdu5834 Magic boy Bi Luo with his excited tree 【树形dp】
- NYOJ 674 善良的国王 -- 树形dp
- 2006 Asia - Kaohsiung Perfect Service 树形DP (uvaLive3685) ★
- CodeForces - 219D Choosing Capital for Treeland(树形dp)