Rebuilding Roads
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 10824 | Accepted: 4988 |
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.
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.
* 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
题目大意,给你n个节点,n-1条边,求保留p个节点的情况下最少需要割除多少条边。
思路及代码参考来源:http://blog.csdn.net/shuangde800/article/details/10150305。感谢大牛。
思路:
1、首先设dp【i】【j】其表示为以i为根节点的子树保留j个节点最少需要割除多少边,sum【i】表示以i为根节点的子树一共有多少个节点,包括i在内。
2、题目保证一棵树,而且经过前辈们的测试以及对后台数据的分析,节点1是永远都作为根节点出现在后台数据中的,所以我们进行树型dp的起点也就确定了。
3、初始化dp【u】【1】=mp【u】.size();然后由状态转移方程:dp【u】【s】=min(dp【u】【s】,dp【v】【j】+dp【u】【s-j】-1)进行动态规划。
4、如果当sum【u】>=p的时候,我们当前的dp【u】【p】就有可能是最终答案,此时维护最小ans。
AC代码:
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
int dp[200][200];
int sum[200];
int n,m,ans;
vector<int >mp[200];
int DP(int u)
{
sum[u]=1;
for(int i=0;i<mp[u].size();i++)//首先解决其子节点的dp问题,和统计其子节点总数的问题。
{
int v=mp[u][i];
sum[u]+=DP(v);
}
dp[u][1]=mp[u].size();
for(int i=0;i<mp[u].size();i++)
{
int v=mp[u][i];
for(int s=sum[u];s>=1;s--)
{
for(int j=1;j<s&&j<=sum[v];j++)
{
dp[u][s]=min(dp[u][s],dp[u][s-j]+dp[v][j]-1);//状态转移方程
}
}
}
if(sum[u]>=m)
{
ans=min(ans,dp[u][m]+(u!=1));//如果当前节点不是根节点,首先当前节点要和其上边的点进行隔断。
}
return sum[u];
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(dp,0x3f3f3f3f,sizeof(dp));
for(int i=0;i<=n;i++)mp[i].clear();
for(int i=0;i<n-1;i++)
{
int u,v;
scanf("%d%d",&u,&v);
mp[u].push_back(v);
}
ans=0x3f3f3f3f;
DP(1);
printf("%d\n",ans);
}
return 0;
}