POJ 1947 Rebuilding Roads(基礎的樹形dp)

畫船聽雨發表於2014-04-29

樹形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;
}


相關文章