首页 > 其他 > 详细

poj1947Rebuilding Roads(树形DP,经典。。。。)

时间:2014-03-19 23:46:45      阅读:673      评论:0      收藏:0      [点我收藏+]

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.] 
dp[p][m]:p表示的是子树的根节点,m表示的是这棵子树恰好有m个节点,dp[][]的值表示断了多少路。
#include<stdio.h>
#include<string.h>
#define inf 1000000
struct nn
{
    int k,son[155];
}node[155];
int dp[155][155],vist[155],N,rootk[155];
int min(int a,int b)
{
    return a>b?b:a;
}
void dfs(int p)
{
      vist[p]=1; rootk[p]=1;
      dp[p][1]=0;
    for(int i=1;i<=node[p].k;i++)
    {
        int son=node[p].son[i];
        if(vist[son])continue;
        dfs(son);   rootk[p]+=rootk[son];

        for(int m=N;m>=1;m--)
        {
            dp[p][m]+=1;//与子点断开
            for(int k=1;k<=rootk[son]&&k<m;k++)//更新与子树连接的情况
            {
               dp[p][m]=min(dp[p][m],dp[p][m-k]+dp[son][k]);
            }
            //printf("%d:(%d,%d)  ",p,m,dp[p][m]);
        }
        for(int k=1;k<=rootk[son];k++) dp[son][k]+=1;//以son为根节点作一棵单独子树与父点点断开,所以需加1
    }

}
int main()
{
    int P,a,b,k,MIN;
    while(scanf("%d%d",&N,&P)>0)
    {
        memset(dp,inf,sizeof(dp));
        memset(vist,0,sizeof(vist));
        for(int i=0;i<=N;i++)
        node[i].k=0;
        for(int i=1;i<N;i++)
        {
            scanf("%d%d",&a,&b);
            node[a].k++; k=node[a].k; node[a].son[k]=b;
            node[b].k++; k=node[b].k; node[b].son[k]=a;
        }
        dfs(1);
        MIN=inf;
        for(int i=1;i<=N;i++)
        if(rootk[i]>=P)
        MIN=min(MIN,dp[i][P]);

        printf("%d\n",MIN);
    }
}


poj1947Rebuilding Roads(树形DP,经典。。。。),布布扣,bubuko.com

poj1947Rebuilding Roads(树形DP,经典。。。。)

原文:http://blog.csdn.net/u010372095/article/details/21556297

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!