前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >H - Partial Tree HDU - 5534 【 完全背包 】

H - Partial Tree HDU - 5534 【 完全背包 】

作者头像
Lokinli
发布2023-03-09 15:10:15
1760
发布2023-03-09 15:10:15
举报
文章被收录于专栏:以终为始以终为始

Partial Tree

H - Partial Tree

HDU - 5534 

Problem Description

In mathematics, and more specifically in graph theory, a tree is an undirected graph in which any two nodes are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. You find a partial tree on the way home. This tree has n nodes but lacks of n−1 edges. You want to complete this tree by adding n−1 edges. There must be exactly one path between any two nodes after adding. As you know, there are nn−2 ways to complete this tree, and you want to make the completed tree as cool as possible. The coolness of a tree is the sum of coolness of its nodes. The coolness of a node is f(d), where f is a predefined function and d is the degree of this node. What's the maximum coolness of the completed tree?

Input

The first line contains an integer T indicating the total number of test cases. Each test case starts with an integer n in one line, then one line with n−1 integers f(1),f(2),…,f(n−1). 1≤T≤2015 2≤n≤2015 0≤f(i)≤10000 There are at most 10 test cases with n>100.

Output

For each test case, please output the maximum coolness of the completed tree in one line.

Sample Input

2 3 2 1 4 5 1 4

Sample Output

5 19

&:把总的度看成是体积,对于 n 个点连成一个 n - 1 时,总的度是 2 * n - 2,因为必须要把所有点都连在一起,所以就可以先假设每个点都有一个度(最小),那样背包的体积就剩余了 n - 2 个了。然后按照完全背包跑就可以了,外层 for 是每个体积对应的贡献度,内层是体积的大小,状态转移方程 dp[ j ] = max( dp[ j ] ,dp[ j - i ] + val[ i + 1 ] - val[ 1 ] );意思是体积 j 的包里可以有两种选择,不拿当前体积为 i 的东西, 那么还是 dp[ j ],如果拿得话,就是体积要减掉 i,得到的贡献值是 val[ i + 1] ,因为相当于是抛弃了原来的那个体积为 1 的物品,这也就是最后面那个地方要减去 val[ 1 ], 那么初始化 dp[ 0 ] = n * val[ 1 ]。

代码语言:javascript
复制
#include<bits/stdc++.h>
using namespace std;
# define ll long long
# define inf 0x3f3f3f3f
const int maxn = 4e4 + 100;
int val[maxn];
int dp[maxn];
int main()
{
    int t,n;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        for(int i = 1; i < n; i ++)
        {
            scanf("%d", &val[i]);
        }
        memset(dp,0,sizeof(dp));
        dp[0] = n * val[1];
        for(int i = 1; i < n - 1; i ++)
        {
            for(int j = i; j <= n - 2; j ++)
            {
                dp[j] = max(dp[j],dp[j - i] + val[i + 1] - val[1]);
            }
        }
        printf("%d\n",dp[n - 2]);
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Partial Tree
    • H - Partial Tree
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档