您的位置:首页 > 产品设计 > UI/UE

POJ 1947-Rebuilding Roads-(树形DP)

2016-05-19 00:04 375 查看
Rebuilding Roads

Time Limit: 1000MSMemory Limit: 30000K
Total Submissions: 10730Accepted: 4939
Description

The cows have reconstructed Farmer John's farm, with its N barns (1 <= N <= 150, number 1..N) after the terrible earthquake last May.

The cows didn't have time to rebuild any extra roads, so now there is exactly one way to get from any given barn to any other barn. Thus,

the farm transportation system can be represented as a tree.

Farmer John wants to know how much damage another earthquake could do. He wants to know the minimum number of roads whose destruction

would isolate a subtree of exactly P (1 <= P <= N) barns from the rest of the barns.
Input

* Line 1: Two integers, N and P

* Lines 2..N: N-1 lines, each with two integers I and J. Node I is node J's parent in the tree of roads.

Output

A single line containing the integer that is the minimum number of roads that need to be destroyed for a subtree of P nodes to be isolated.

Sample Input
11 6
1 2
1 3
1 4
1 5
2 6
2 7
2 8
4 9
4 10
4 11

Sample Output
2

Hint

[A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.]

题意:给你一颗树,求出分解出一颗节点数为p的子树需要切几刀

思路:树形DP+01背包。网上的代码胡乱的来,什么初始化什么乱来的语

句什么鬼,写的不规范,迫于无奈自己写了这份代码。

/*
状态转移方程:dp[u][i + j] = min(dp[u][j + i], dp[v][j] + dp[u][i] - 1);
dp[u]
:u表示当前节点,第二个参数表示u节点分出n个节点的子树,dp[u]
就表示了向下需要多少道,注意是向下!
*/

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 200;
const int inf = 0x3f3f3f3f-5;
int dp[maxn][maxn], num[maxn], n, p;		//num表示当前节点有几个孩子
int head[maxn], tol = 0;
bool vis[maxn];						//用于找根爸爸
struct node
{
int v, next;
}edge[maxn];

void add(int u, int v)
{
num[u]++;
edge[tol].v = v;
edge[tol].next = head[u];
head[u] = tol++;
}

void init()
{
memset(vis, 0, sizeof(vis));
memset(num, 0, sizeof(num));
memset(head, -1, sizeof(head));
tol=0;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= p; j++)
dp[i][j] = inf;
}

void dfs(int u)
{
dp[u][1] = num[u];
for (int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
dfs(v);
for (int i = p - 1; i >= 1; i--)
{
for (int j = 1; j + i <= p; j++)
{
if (dp[v][j] != inf&&dp[u][i] != inf)
dp[u][i + j] = min(dp[u][j + i], dp[v][j] + dp[u][i] - 1);
}
}
}

}

int main()
{
while (scanf("%d%d", &n, &p) != EOF)
{
init();
for (int i = 1; i < n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
vis[v] = true;
add(u, v);
}
int ans = 0;
for (int i = 1; i <= n; i++)
if (!vis[i])
{
dfs(i);
ans = dp[i][p];
break;
}
for (int i = 1; i <= n; i++)
if (vis[i])
ans = min(ans, dp[i][p] + 1);		//+1是为了与爸爸断绝,呼应了上面的向下切刀
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: