题目描述:
Partial Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 222 Accepted Submission(s): 133
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
题解:
真是很好很好的一道题啊.
法一:首先是一个比较正常的解法:
从度入手.f[i]表示答案.i个点一共度2*i-2.刚开始每个点假设都有一个度,因为要保证联通.然后剩下n-2个自由的度,想给哪一个点就给哪一个点,也就是想怎么划分就怎么划分.价值并不是原题意的价值,而是花i的度可购买g[i+1]-g[1]的价值.
法二:其次是一个比较奇怪的:
发现一个现象,几个点合成一小堆之后,这个小堆就相当于一个新的点.而一个新的点又可以参与合并,并且效果是一样的.因此可以达到我们缩小规模的作用.
我们对于i的规模,暴力枚举它最靠下面的叶子那一层合成的第一个节点有多少个儿子,因为它之后一定会再往上连,那么他对于以后的增值可以算出.而有一个特殊情况,如果只有两层,特殊算一下就好.
重点:
如何消耗点,并且维护一个一直可以使用的结构.
技巧:找特殊点消耗.并且一堆点看成一个新点
技巧:从度来考虑.并且树的话先联通,每个有度1.
代码:
//这是法二
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
const int maxn = 3000+10;
int f[maxn], n, g[maxn];
void solve()
{
g[1] = 0;
for(int i = 1;i<=n;i++)
{
g[i] = -1;
for(int j = 1;j<=i-2;j++)
{
g[i] = max(g[i], f[j+1]+f[1]*j-f[1]+g[i-j]);
}
g[i] = max(g[i], f[1]*(i-1)+f[i-1]);
//printf("%d %d\n", i, g[i]);
}
printf("%d\n", g[n]);
}
int main()
{
// freopen("Hin.txt", "r", stdin);
int ncase;
scanf("%d", &ncase);
while(ncase--)
{
scanf("%d", &n);
f[0] = 0;
for(int i = 1;i<=n-1;i++)
{
scanf("%d", &f[i]);
}
solve();
}
return 0;
}