1. 程式人生 > >Partial Tree HDU

Partial Tree HDU

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
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

#define rep(i,a,b) for(int i=a;i<b;++i)

const int N=2100;
const int INF=0x3f3f3f3f;

int val[N];

int dp[N];
/*
n^3的複雜度,比較好像,然後就是降維了,降維意味著需要改變一些初始值
我們假設全部的點都用度為1的點來組成
然後我們採用一種替代的思想,每次我們選一個點都會替代一個度為1的點,所以說其實我們
一直都是在n個點,這個維度上dp,根本不用去dp這個n.
剩下的就是完全揹包了。
*/
int main(){
	int T;
	scanf("%d",&T);
    while(T--){
		int n;
		scanf("%d",&n);

		rep(i,1,n)scanf("%d",&val[i]);

		fill(dp,dp+n,-INF);
		dp[0]=n*val[1];//初始化,已經是n個點
		
		for(int i=2;i<n;i++){
			for(int j=i-1;j<=n-2;j++){
				if(dp[j-(i-1)]==-INF)continue;
				dp[j]=max(dp[j],dp[j-(i-1)]+val[i]-val[1]);
			}
		}
		
		printf("%d\n",dp[n-2]);
    }
    return 0;
}