題目:這裏php
題意:node
感受並不能表達清楚題意,因此ios
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
Sample Output
首先,這個最終答案是與點的度有關,因爲是個樹,能夠知道最後全部點的度數和是n*2-2,還有,每一個點至少得有一個度,因此最終答案得先加上f[1]*n,而後如今
還剩下n-2個度,須要在n個點裏分配,使得分配以後的權值最大,可是這個分配因爲是有關聯的,一個點的度數加了1以後必須得有另外一個點的度數也加1,因此咱們的
分配方案還得知足這個條件,不能隨意分配,可是經過隨意取幾個n值構造一下樹發現,n-2個度任意分給n個點的方案可以知足構造出一棵樹,並且這個構造還挺有
規律,有遞推性,因此大膽認爲能夠任意分配,好,如今n-2個度分配給n個點,每次能夠分配1到n-1個度,問怎麼分配值f()最大,這不就是一個揹包麼,仍是一個徹底
揹包。再注意一下這是在每一個點已經有了一個度的前提下,因此得減去f[1]。
1 #include<cstdio>
2 #include<cstring>
3 #include<iostream>
4 #include<algorithm>
5 using namespace std;
6
7 #define inf 0x3f3f3f3f
8 const int M = 1e4 + 10;
9 int dp[M],a[M];
10
11 int max(int x,int y){return x>y?x:y;}
12
13 int main()
14 {
15 int t,n;
16 scanf("%d",&t);
17 while (t--){
18 scanf("%d",&n);
19 for (int i=1 ; i<n ; i++) {
20 scanf("%d",&a[i]);
21 if (i!=1) a[i]-=a[1];
22 }
23 //int pa=n*2-2;
24 for (int i=0 ; i<=n ; i++) dp[i]=-inf;
25 dp[0]=0;//dp[1]=a[1];
26 for (int i=2 ; i<n ; i++) {
27 for (int j=0 ; j+i-1<=n-2 ; j++)
28 dp[i+j-1] = max(dp[i+j-1],dp[j]+a[i]);
29 }
30 printf("%d\n",dp[n-2]+n*a[1]);
31 }
32 return 0;
33 }