POJ 1947 Rebuilding Roads 树形DP

Rebuilding Roads
 

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

题意:

  给你一个n点的树和一个p

  问你通过删除一些边得到一个至少含有一个子树节点数为p的最少删除数

题解:

  设定dp[u][x]表示以u为根节点剩余x个点的最少删除边数

  那么这就是背包问题了

  dp[u][i] = min(dp[v][k]+dp[u][i-k]-1,dp[u][i]);

  u表示根节点,v表示儿子之一

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include<vector>
#include <algorithm>
using namespace std;
const int N = 2e2+20, M = 1e2+10, mod = 1e9+7, inf = 1e9+1000;
typedef long long ll;

int siz[N],n,p,dp[N][N];
vector<int > G[N];
void dfs(int u,int fa) {
    siz[u] = 1;
    int totson = G[u].size();
    for(int i=0;i<totson;i++) {
        int to = G[u][i];
        if(to == fa) continue;
        dfs(to,u);
        siz[u] += siz[to];
    }
    dp[u][1] = totson - 1;if(u == 1) dp[u][1]++;
    for(int j=0;j<totson;j++) {
        int v = G[u][j];
        if(v == fa) continue;
        for(int i=siz[u];i>=1;i--) {
            for(int k=1;k<i && k<=siz[v];k++) {
                dp[u][i] = min(dp[v][k]+dp[u][i-k]-1,dp[u][i]);
            }
        }
    }
}
int main()
{
    scanf("%d%d",&n,&p);
    for(int i=1;i<n;i++) {
        int a,b;
        scanf("%d%d",&a,&b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    for(int i=0;i<=n;i++) for(int j=0;j<=p;j++) dp[i][j]=inf;
    dfs(1,-1);
    int ans = dp[1][p];
    for(int i=2;i<=n;i++) {
        ans = min(ans, dp[i][p]+1);
    }
    cout<<ans<<endl;
}

 

转载于:https://www.cnblogs.com/zxhl/p/5688642.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值