HDU 5534 - Partial Tree(完全背包)【真*好题】

Partial Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 2087    Accepted Submission(s): 1035


 

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

 

 

Source

2015ACM/ICPC亚洲区长春站-重现赛(感谢东北师大)

 

 

Recommend

hujie   |   We have carefully selected several similar problems for you:  6447 6446 6445 6444 6443 

 

 

Statistic | Submit | Discuss | Note

 

思路:刚开始一看就以为是树形DP,想着凉了。后来仔细思考了一下,看着像是背包。

对于一张图G,n个结点,n-1条边,则各个结点的度的和 sum = (n-1) * 2;这里,sum 就相当于背包的容量 V 。各个点的度和权值就相当于物品的体积和价值。我们这样就把问题转化成了一个完全背包。

但是,如果直接变成一个完全背包的话是错误的,因为有些结点可能没有选(这样就不能构成一棵树了)。

所以我们进行一波骚操作:

把所有点的度初始都设定为a[1],初始的权值和为 a[1]*n(即dp[0])。

这样,我们之后只要使得度数之和变成(n-2)即可。

dp[i]表示度数为 i 条件下的最大收益。

状态转移方程:dp[i] = max( dp[i-k] + a[k+1] - a[1] )。意思是,我们想要更新度数为i的最大权值,我们会想着它可以基于之前的一个度数,然后把一个未扩展的子节点扩展a[k+1]-a[1]的权值。

  1. 我们有n个点可以扩展度数,而可能扩展的总度数只有n-2,所以一定不会出现多次扩展的情况

  2. 每个点都有一个为1的基准度,一定有办法把它们恰好拼成一棵树。

 

 

#pragma GCC optimize(2)
#include 
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define line cout<<"-----------------"<

 

你可能感兴趣的:(背包问题,HDU)