现在的位置: 首页 > 综合 > 正文

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

2018年02月22日 ⁄ 综合 ⁄ 共 1787字 ⁄ 字号 评论关闭

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);
    }
}

抱歉!评论已关闭.