POJ 1947 Rebuilding Roads(基础的树形dp)

126 篇文章 2 订阅

树形dp,dp[i][j]中i表示节点i,j表示这个节点下面有多少点。dp表示此时最少删掉了多少边。如果子节点删除那么dp[i][j]+1,不删除就不用管。dp[i][j] = min(dp[i][j]+1,  min(dp[i][k]+dp[t][j-k])).t表示i的子节点。

Rebuilding Roads
Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 8729 Accepted: 3935

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
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define eps 1e-8
#define M 1000100
//#define LL __int64
#define LL long long
#define INF 0x3f3f3f3f
#define PI 3.1415926535898

const int maxn =200;
using namespace std;

int dp[maxn][maxn];
int num[maxn];
vector<int>g[maxn];
int n, m;
void dfs(int x)
{
    for(int i = 0; i <= m; i++)
        dp[x][i] = INF;
    dp[x][1] = 0;
    for(int i = 0; i < g[x].size(); i++)
        dfs(g[x][i]);
    if(g[x].size() == 0)
        return;
    for(int i = 0; i < g[x].size(); i++)
    {
        for(int j = m; j >= 0; j--)
        {
            int Min = INF;
            for(int k = 0; k < j; k++)
                Min = min(Min, dp[x][k] + dp[g[x][i]][j-k]);
            dp[x][j] = min(dp[x][j]+1, Min);
        }
    }
}

int main()
{
    while(~scanf("%d",&n))
    {
        scanf("%d",&m);
        for(int i = 0; i <= n; i++)
            g[i].clear();
        int x, y;
        for(int i = 0; i < n-1; i++)
        {
            cin >>x>>y;
            g[x].push_back(y);
        }
        dfs(1);
        int ans = dp[1][m];
        for(int i = 2; i <= n; i++)
            ans = min(ans, dp[i][m]+1);
        cout<<ans<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值