Partial Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 2649 Accepted Submission(s): 1296
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
题意:给n-1个点,每个点有个权值和这个点连接的边的数量(从1到n-1)现在从里面选取n个点(可以多次选取)构成一颗树,求出最大权值。
例如:
4
5 1 4
第一条边权值为5,连接的边为1
第二条边权值为1,连接的边为2
第三条边权值为4,连接的边为3
权值最大情况为权值为4的点连接3个权值为5的点。
思路:对于任何一棵树,他的总边数是确定的,即边数=n-1,那么想构成一棵树,需要满足选取的点个数i=n,选取点的degree总和=2*(n-2)。
很容易想到一个完全背包,i表示选取了i个点,j表示已经选取点的degree总和,那么dp[i][j]=max(dp[i][j],dp[i-1][j-v[k]]+w[k])
for (int i = 1; i <= n; ++i) {
for (int k = 0; k < n-1; ++k) {
for (int j = a[k].d; j <= v; ++j) {
dp[i][j]=max(dp[i][j],dp[i-1][j-a[k].d]+a[k].w);
}
}
}
想法很好,但是不可行。2000*2000*4000*t的复杂度显然会超时。
那么我们需要优化一下,三个循环必会T,只有优化到两重循环,那么考虑一下i和j的关系,只有将i和j合并到一起,才能实现两重循环。
i表示选取了i个点,j表示degree总和,i最终应该等于n,j最终应该等于2*n-2,容易看出,每选取一个新的节点,i的增量固定为1,而j的增量是不确定的,那么我先选n个degree=1的节点,此时j=n,距离目标2*n-2还差n-2,因为n个节点已经全部选了,只用考虑将degree增加到2*n-2即可,总增量=n-2。
预处理每个节点对于第一个节点的权值增量,degree增量,问题变成简单的完全背包。
#include"bits/stdc++.h"
using namespace std;
int dp[2020];
const int inf=0x3f3f3f3f;
struct node
{
int d,w;
}a[2020];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
memset(dp,-inf,sizeof(dp));
scanf("%d",&n);
for (int i = 0; i < n-1; ++i) {
scanf("%d",&a[i].w);
a[i].d=i;
}
dp[0]=n*a[0].w;
for (int i = 1; i < n-1; ++i) {
a[i].w-=a[0].w;
}
for (int i = 1; i < n-1; ++i) {
for (int j = a[i].d; j <= n-2; ++j) {
dp[j]=max(dp[j],dp[j-a[i].d]+a[i].w);
}
}
printf("%d\n",dp[n-2]);
}
}