poj1947 Rebuilding Roads(트리 DP, 클래식...)

2717 단어 dp
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
",MIN); } }

좋은 웹페이지 즐겨찾기