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

POJ 1947 Rebuilding Roads

2015-09-07 20:41 337 查看

Rebuilding Roads

Time Limit: 1000ms
Memory Limit: 30000KB
This problem will be judged on PKU. Original ID: 1947
64-bit integer IO format: %lld Java class name: Main

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.]

Source

USACO 2002 February

解题:树形dp

dp[i][j]表示以i为根保留j个点最少需要去掉多少条边

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 200;
int n,k,ret,dp[maxn][maxn],son[maxn];
vector<int>g[maxn];
int dfs(int u){
son[u] = 1;
for(int i = g[u].size()-1; i >= 0; --i) son[u] += dfs(g[u][i]);
dp[u][1] = g[u].size();//u有g[u].size()个直系儿子 删除儿子还剩自己
for(int i = g[u].size()-1; i >= 0; --i){
for(int j = son[u]; j > 0; --j)
for(int k = 1; k < j && k <= son[g[u][i]]; ++k)
dp[u][j] = min(dp[u][j],dp[u][j - k] + dp[g[u][i]][k] - 1);
}
if(son[u] >= k) ret = min(ret,dp[u][k] + (u != 1));
return son[u];
}
int main(){
int u,v;
while(~scanf("%d%d",&n,&k)){
for(int i = 0; i < maxn; ++i) g[i].clear();
for(int i = 1; i < n; ++i){
scanf("%d%d",&u,&v);
g[u].push_back(v);
}
memset(dp,0x3f,sizeof dp);
memset(&ret,0x3f,sizeof ret);
dfs(1);
printf("%d\n",ret);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: