地址:http://poj.org/problem?id=1947
Rebuilding Roads
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 8965 | Accepted: 4043 |
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.]
题意:问要得到一个节点数为p的子树,最少要割多少条边。
思路:注意两点:不要同时割掉一棵树的子树以及其子树的子树,这样会重复;任意一个点都可以为根。
代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define Ma 155
#define INF 0xfffffff
#define LL __int64
struct node
{
int to,next;
} tree[Ma*2];
int n,p,len,head[Ma],son[Ma],dp[Ma];
void add(int no,int to)
{
tree[len].to=to;
tree[len].next=head[no];
head[no]=len++;
}
void dfs(int no,int pa)
{
int ss[Ma];
for(int i=0; i<=n; i++) ss[i]=dp[i]; //记录目前的最优值,新建ss数组是因为直接在DP数组上记录会重复割掉已经割掉的点
for(int i=head[no]; i!=-1; i=tree[i].next)
{
int to=tree[i].to;
if(to==pa) continue;
dfs(to,no);
son[no]+=son[to];
}
for(int i=0; i<=n-son[no]; i++)
ss[i]=min(ss[i],ss[i+son[no]]+1);
for(int i=0; i<=n; i++) //在最后把最优值记录到DP数组上
dp[i]=min(dp[i],ss[i]);
}
int main()
{
while(scanf("%d%d",&n,&p)>0)
{
memset(head,-1,sizeof(head));
len=0;
for(int i=1; i<n; i++)
{
int l,r;
scanf("%d%d",&l,&r);
add(l,r);
add(r,l);
}
int minn=INF;
for(int i=1; i<=n; i++) //这里循环n次表示以i为根节点
{
for(int j=0; j<=n; j++)
{
son[j]=1;
dp[j]=INF;
}
dp[n]=0;
dfs(i,-1);
minn=min(minn,dp[p]);
}
printf("%d\n",minn);
}
return 0;
}