2015長春H Partial Tree(完全揹包思維)
9262: Partial Tree
時間限制: 1 Sec 記憶體限制: 128 MB
提交: 35 解決: 14
[提交] [狀態] [討論版] [命題人:admin]
題目描述
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?
輸入
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.
輸出
For each test case, please output the maximum coolness of the completed tree in one line.
樣例輸入
2
3
2 1
4
5 1 4
樣例輸出
5
19
來源/分類
【題意】
給出一個數列a[],讓我們構造一棵n點的樹,點i的度為x,則點i的價值為a[x],求最大的n個點價值之和。
【分析】
容易知道,一棵樹總共有2n-2個度,而且這棵樹每個點必須至少有一個度,那我們就先給每個點一個度。剩下n-2個度可以自由分配。用動態規劃去分配這n-2個度,求出最大值。
設dp[i]表示分配了i個度的最優值。初始狀態dp[0]表示已經給每個點分配了一個度,故dp[0]=n*a[1];
我們的揹包容量就是n-2,n-2個度分配給n個點,可能是給某個點分1度、2度或者i度,為某個點分配上i個度,則其度從1變為i+1。 分配i個度可能分配多次,故完全揹包可解。dp[j]=max(dp[j-i]+a[i+1]-a[1]);
【程式碼】
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[2020];
int a[2020],n,T;
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<n;i++)scanf("%d",&a[i]);
for(int i=0;i<=n-2;i++)dp[i]=-1e9;
dp[0]=n*a[1];
for(int i=1;i<=n-2;i++)
{
for(int j=i;j<=n-2;j++)
dp[j]=max(dp[j],dp[j-i]+a[i+1]-a[1]);
}
printf("%lld\n",dp[n-2]);
}
}