Rebuilding Roads
| Time Limit: 1000MS |
|
Memory Limit: 30000K |
| Total Submissions: 1146 |
|
Accepted: 390 |
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.]
Source
题目给出了一个树节点数为n,要求去掉最少的边,得出一个子树,使得这个子树的节点树为m。
首先这是一棵无根树,任意一个节点都可以作为根。这里就去1号节点为根。考虑除根节点外,树中的每一个节点。一种情况是在dfs时,该节点脱离它的父节点,由它和它的子节点共同组成一棵子树,这样要把边删掉;另一种情况是保持该节点与其父节点的连接,不要删边。在做dfs的时候,对于当前节点v,计算所有子节点产生的dp值。dp[i][j]表示第i个节点为根,生成节点数为j的子树所需要删掉的最小边的条数。最后还要注意整颗树的根节点因为它没有父节点,所以不用计算删除的边。
dfs做dp的过程如下:
1
void search(int v)
2

{
3
int i,j,k,t;
4
mark[v]=true;
5
dp[v][0]=1;
6
dp[v][num[v]]=0;
7
for(i=1; i<=n; i++)
8
{
9
if(g[v][i] && !mark[i])
10
{
11
search(i);
12
for(j=1; j<=num[v]; j++)
13
{
14
if(dp[v][j] != INF)
15
{
16
for(k=0; k<=num[i]; k++)
17
{
18
if(dp[i][k] != INF)
19
{
20
t=dp[v][j-(num[i]-k)];
21
dp[v][j-(num[i]-k)]=Min(t,dp[v][j]+dp[i][k]);
22
}
23
}
24
}
25
}
26
}
27
}
28
}
29
30
int main()
31

{
32
int i,j,a,b;
33
//freopen("in.txt","r",stdin);
34
scanf("%d%d",&n,&m);
35
memset(g,false,sizeof(g));
36
memset(num,0,sizeof(num));
37
for(i=1; i<=n; i++)
38
for(j=1; j<=n; j++)
39
dp[i][j]=INF;
40
for(i=1; i<n; i++)
41
{
42
scanf("%d%d",&a,&b);
43
g[a][b]=g[b][a]=true;
44
}
45
memset(mark,false,sizeof(mark));
46
dfs(1);
47
memset(mark,false,sizeof(mark));
48
search(1);
49
a=INF;
50
for(i=1; i<=n; i++)
51
{
52
//for(j=1; j<=num[i]; j++)
53
//{
54
b=dp[i][m];
55
if(i != 1)
56
b++;
57
if(b < a)
58
a=b;
59
//}
60
}
61
printf("%d\n",a);
62
return 0;
63
}
posted on 2008-05-05 17:38
飞飞 阅读(999)
评论(0) 编辑 收藏 引用 所属分类:
ACM/ICPC