zoukankan      html  css  js  c++  java
  • Rebuilding Roads

    描述

    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.

    输入

    * 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.

     输出

    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.

    样例输入

    11 6
    1 2
    1 3
    1 4
    1 5
    2 6
    2 7
    2 8
    4 9
    4 10
    4 11

    样例输出

    2

    题目大意:一棵树至少去掉几条边可以形成大小为p的子树

    解题思路:树形dp,状态转移方程dp[root][j]=min(dp[root][j],dp[root][j-k]+dp[G[root][i]][k]-2)

    #include <bits/stdc++.h>
    #define LL long long
    #define INF 0x3f3f3f3f
    using namespace std;
    const int N=200;
    int dis[N],dp[N][N],n,p;//dp[i][j]表示以i为根节点的子树形成j个结点需要去掉的边数 
    vector<int>G[N];
    void dfs(int root)
    {
        for(int i=0;i<G[root].size();i++){
            dfs(G[root][i]);
            for(int j=p;j>1;j--){
                for(int k=1;k<j;k++){
                    dp[root][j]=min(dp[root][j],dp[root][j-k]+dp[G[root][i]][k]-2); 
                }
            }
        }
    }
    int main()
    {
        memset(dp,INF,sizeof(dp));
        scanf("%d%d",&n,&p);
        for(int i=1,u,v;i<n;i++){
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            dis[v]++;
        }
        int root;
        for(int i=1;i<=n;i++) dp[i][1]=G[i].size()+1;
        for(int i=1;i<=n;i++){
            if(dis[i]==0){
                root=i;break;
            }
        }
        dfs(root);
        dp[root][p]--;
        int ans=INF;
        for(int i=1;i<=n;i++){
            ans=min(ans,dp[i][p]);
        }
        cout<<ans<<endl;
    }
  • 相关阅读:
    HereDOC案例
    array_number
    CodeMirror---实现关键词高亮
    webstorage的使用
    vue.js--绑定方法到window对象
    docker部署服务实现文件上传到本地问题解决
    ES6之map与set
    JAVA生成视频缩略图的两种方式
    vuex状态管理
    ELK日志分析平台
  • 原文地址:https://www.cnblogs.com/ww123/p/11638306.html
Copyright © 2011-2022 走看看