• 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;
            
        }
    }
     
  • 相关阅读:
    如何利用c++读取.doc文档
    C++经典面试题(验证你的C++水准)
    与你初识
    VS2005发布项目
    请教一:OpenGL旋转
    数据备份和故障修复文件历史记录
    数据备份和故障修复备份与还原
    使用Windows 8 的“任务计划”令HydraVision更加精彩
    Windows 恢复环境(Windows RE模式)
    Unsupported major.minor version 49.0错误处理
  • 原文地址:https://www.cnblogs.com/ww123/p/11751633.html
Copyright © 2020-2023  润新知