zoukankan      html  css  js  c++  java
  • Tree of Tree

    描述

    You're given a tree with weights of each node, you need to find the maximum subtree of specified size of this tree.

    Tree Definition
    A tree is a connected graph which contains no cycles.

    输入

    There are several test cases in the input.

    The first line of each case are two integers N(1 <= N <= 100), K(1 <= K <= N), where N is the number of nodes of this tree, and K is the subtree's size, followed by a line with N nonnegative integers, where the k-th integer indicates the weight of k-th node. The following N - 1 lines describe the tree, each line are two integers which means there is an edge between these two nodes. All indices above are zero-base and it is guaranteed that the description of the tree is correct.

    输出

    One line with a single integer for each case, which is the total weights of the maximum subtree.

    样例输入

    3 1
    10 20 30
    0 1
    0 2
    3 2
    10 20 30
    0 1
    0 2

    样例输出

    30

    40

    题目大意:给定一颗树,求结点数为k的子树的最大权值。

    解题思路:树形dp,dp[i][j]表示以第i个结点为根,有j个结点的子树的最大权值。

    #include <bits/stdc++.h>
    using namespace std;
    #define LL long long
    const int N=105;
    vector<int>G[N];
    int dp[N][N],m,d[N],a[N];
    void dfs(int u)
    {
        dp[u][1]=a[u];
        for(int i=0;i<G[u].size();i++){
            int v=G[u][i];
            dfs(v);
            for(int j=m;j>=1;j--){
                for(int k=1;k<=j;k++){
                    if(j-k>=0) dp[u][j]=max(dp[u][j],dp[u][k]+dp[v][j-k]);
                }
            }
        }
    
    }
    int main()
    {
        int n;
        while(cin>>n>>m){
            for(int i=0;i<=n;i++){
                G[i].clear();d[i]=0;
                for(int j=0;j<=m;j++) dp[i][j]=0;
            }
            for(int i=0;i<n;i++) cin>>a[i];
            for(int i=1,u,v;i<n;i++){
                cin>>u>>v;
                G[u].push_back(v);
                d[v]++; 
            }
            int pos=-1;
            for(int i=0;i<n;i++) if(d[i]==0) dfs(i);
            int ans=-1;
        
            for(int i=0;i<n;i++) ans=max(ans,dp[i][m]);
            cout<<ans<<endl;
            
        }
    }
     
  • 相关阅读:
    Mysql TEXT类型长度
    php中的||和or的区别 优先级
    常用的排序算法的时间复杂度和空间复杂度
    ThinkPHP 多应用多模块建立方式
    phpcms v9 后台添加修改页面空白页问题解决方法
    linux中nginx重定向方法总结
    Nginx的主要配置参数说明
    Apache多网站虚拟目录域名
    xampp命令
    (转载)处理SQL解析失败导致share pool 的争用
  • 原文地址:https://www.cnblogs.com/ww123/p/11751633.html
Copyright © 2011-2022 走看看