Partial Tree ICPC 2015 Changchun 完全揹包
9262: Partial Tree
時間限制: 1 Sec 記憶體限制: 128 MB 提交: 70 解決: 29 [提交] [狀態] [討論版] [命題人: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
來源/分類
比賽時看到這道題感覺是窒息的,但是賽後看題解更窒息,完全想不到是個揹包,極其震驚
題意:給n各點,分配n-1條邊,使每個點的度i對應的f( i )相加的和最大,f(i)給出
思路:大佬說,不管怎麼建樹,只要能夠保證每個點的度至少為一,那麼總是存在一棵樹滿足你的度數分配要求,那麼只需要把
度數分配下去,並且每個點的度數至少為1,所以先給每個點都分配1的度數,所以最初的2n-2的度數就剩下了n-2的度數。
然後就可以看作完全揹包的問題,把n-2總度數看作總空間的體積,每個i為體積,f(i)為對應的權值,然後在滿足總體積的前提
下讓權值最大
程式碼:
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int maxn = 1e4+10;
const int inf = 0x3f3f3f3f;
typedef long long ll;
ll f[maxn],dp[maxn];
int main() {
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
for(int i=1; i<n; i++){
scanf("%lld",&f[i]);
dp[i]=-inf;
}
dp[n]=-inf;
dp[0]=f[1]*n;
for(int i=1; i<n-1; i++){
for(int j=i; j<=n-2; j++){
dp[j]=max(dp[j],dp[j-i]+f[i+1]-f[1]);
}
}
printf("%lld\n",dp[n-2]);
}
return 0;
}