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;
    }
  • 相关阅读:
    聊聊部署在docker容器里面的springboot项目如何启用arthas
    如何低侵入的记录调用日志
    聊聊如何在spring事务中正确进行远程调用
    聊聊因不恰当使用alibaba sentinel而踩到的坑
    SqlServer行转列关键字——Pivot
    [转] 为后人挖坑指南
    动态加载js并调用其中指定名称方法
    Html网页模态居中弹窗
    SqlServer 要了解死锁必须学会制造死锁
    SqlServer中的(分区)表文件组
  • 原文地址:https://www.cnblogs.com/ww123/p/11638306.html
Copyright © 2011-2022 走看看