POJ 1947 Rebuilding Roads 题解【树形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.]

题意简述

给一棵n节点的树,问至少要砍多少条边才可以使其成为一棵节点为p的树

解题思路

  1. 可以知道若只有一个结点,那不需要砍边则可以成为一棵结点数为1的树
  2. 对于以i为根的某棵子树,除了它自身提供一个结点,其他结点由它的子结点提供,而与树的其他部分无关,满足无后效性,考虑DP
  3. 以f[i][j]记录以i为根结点的子树,则f[i][j]=f[i][j-k]+f[v][k],v为i的子结点
  4. 初始化,f[i][0]=1(直接砍掉父边),f[i][1]=0

AC代码

#include
#include
#include
#include
#include
using namespace std;

const int maxn=155,oo=0x3f3f3f3f;
int ans,n,m,c,root;
int f[maxn][maxn],head[maxn],fa[maxn];
bool flag[maxn];
struct note{
    int v,next;
}a[maxn];

void addedge(int x,int y)
{
    a[++c].v=y;a[c].next=head[x];head[x]=c;
}

void dfs(int u)
{
    f[u][0]=1;
    f[u][1]=0;
    for (int i=head[u];~i;i=a[i].next)
    {
        int v=a[i].v;
        dfs(v);
        for (int j=m;j>=1;j--)
        {
            int tmp=oo;
            for (int k=0;kint main()
{   
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    memset(f,0x3f,sizeof(f));
    for(int i=1;iint x,y;
        scanf("%d%d",&x,&y);
        fa[y]=x;
        addedge(x,y);
        flag[y]=1;
    }

    for (int i=1;i<=n;i++)
      if (!flag[i]) 
      {
         dfs(i);
         root=i;
      }

    ans=oo;
    for (int i=1;i<=n;i++)
      if (i!=root) ans=min(ans,f[i][m]+1);
        else ans=min(ans,f[i][m]);
    printf("%d\n",ans);

    return 0;
}

小技巧

  1. 无后效性考虑DP
  2. 对于某个状态,考虑哪些状态能够影响它

你可能感兴趣的:(poj,dp,NOIP,C++,题解,DP,POJ)