POJ 1947 Rebuilding Roads 题解【树形DP】

8 篇文章 0 订阅
8 篇文章 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.]

题意简述

给一棵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<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
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;k<j;k++)
              tmp=min(f[u][j-k]+f[v][k],tmp);
            f[u][j]=tmp;
        }
    }
}

int main()
{   
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    memset(f,0x3f,sizeof(f));
    for(int i=1;i<n;i++)
    {
        int 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. 对于某个状态,考虑哪些状态能够影响它
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值