1. 程式人生 > >HDU - 5534 Partial Tree(每種都裝的完全背包)

HDU - 5534 Partial Tree(每種都裝的完全背包)

words first dir with org sta eas -s ++

Partial Tree

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 nn nodes but lacks of
n1n−1 edges. You want to complete this tree by adding n1n−1edges. There must be exactly one path between any two nodes after adding. As you know, there are nn2nn−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)f(d), where ff is a predefined function and dd is the degree of this node. What‘s the maximum coolness of the completed tree?

InputThe first line contains an integer TT indicating the total number of test cases.
Each test case starts with an integer nn in one line,
then one line with n1

n−1 integers f(1),f(2),,f(n1)f(1),f(2),…,f(n−1).

1T20151≤T≤2015
2n20152≤n≤2015
0f(i)100000≤f(i)≤10000
There are at most 1010 test cases with n>100n>100.
OutputFor 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




因為每種裝的範圍為【1,+無窮】,然而分組背包的三次方會T,所以要想辦法將其轉化為完全背包模型。
因為每個點都至少有一度,所以我們預先放入n個一度,本來要放的2×n-2度現在只剩n-2度。
每當再次放入一個x度時,他的貢獻為x-1度,在放入的同時減掉之前預先放好的一度。這樣便保證了每個點至少有一度。

#include<bits/stdc++.h>
#define MAX 2018
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;

int a[MAX];
ll dp[MAX];

int main()
{
    int t,n,m,i,j,k;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(i=1;i<n;i++){
            scanf("%d",&a[i]);
        }
        memset(dp,-INF,sizeof(dp));
        dp[0]=0;
        for(i=2;i<n;i++){
            for(j=i-1;j<=n-2;j++){
                dp[j]=max(dp[j],dp[j-(i-1)]+a[i]-a[1]);
            }
        }
        printf("%I64d\n",dp[n-2]+n*a[1]);
    }
    return 0;
}
 

HDU - 5534 Partial Tree(每種都裝的完全背包)