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
注意到一个节点数为n的树的度数和为2*n-2,所以问题就转换为了把2*n-2个度分配给n个节点所能获得的最大价值,而且每一个节点至少分到1个度。我们可以先每一个分一个度,然后把n-2个节点任意分配完。分配的时候因为已经分了1个度了,所以要把2~n-1的度看为1~n-1,然后做个完全背包就行了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #pragma comment(linker, "/STACK:1024000000,1024000000") 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 #include<math.h> 7 #include<algorithm> 8 #include<queue> 9 #include<set> 10 #include<bitset> 11 #include<map> 12 #include<vector> 13 #include<stdlib.h> 14 #include <stack> 15 using namespace std; 16 #define PI acos(-1.0) 17 #define max(a,b) (a) > (b) ? (a) : (b) 18 #define min(a,b) (a) < (b) ? (a) : (b) 19 #define ll long long 20 #define eps 1e-10 21 #define MOD 1000000007 22 #define N 2116 23 #define inf 1e12 24 int n; 25 int f[N],dp[N]; 26 int main() 27 { 28 int t; 29 scanf("%d",&t); 30 while(t--){ 31 scanf("%d",&n); 32 for(int i=1;i<=n-1;i++){ 33 scanf("%d",&f[i]); 34 } 35 int ans=0; 36 ans+=f[1]*n; 37 for(int i=2;i<=n-1;i++){ 38 f[i]-=f[1]; 39 } 40 for(int i=1;i<=n-2;i++){ 41 f[i]=f[i+1]; 42 } 43 //memset(dp,0,sizeof(dp)); 44 for(int i=0;i<N;i++){ 45 dp[i]=-inf; 46 } 47 dp[0]=0; 48 for(int i=1;i<=n-2;i++){ 49 for(int j=i;j<=n-2;j++){ 50 dp[j]=max(dp[j],dp[j-i]+f[i]); 51 } 52 } 53 ans+=dp[n-2]; 54 printf("%d ",ans); 55 } 56 return 0; 57 }