hdu 5534 Partial Tree 揹包DP

參考:http://www.cnblogs.com/qscqesze/p/4967071.htmlhttp://blog.csdn.net/qq_21057881/article/details/52598441

Partial Tree

Time Limit: 20 Sec

Memory Limit: 256 MB
題目連接

http://acm.hdu.edu.cn/showproblem.php?pid=5534
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

2
3
2 1
4
5 1 4

Sample Output

5
19
HINT

題意

給你n個點,讓你構造出一棵樹

假設這棵樹最後度數爲k的點有num[k]個,那麼這棵樹的價值爲sigma(num[i]*f[i])

其中f[i]是已經給定的

思路:一棵樹有2(n-1)個度,每個度都有它的權值,那麼就相當於一個容量爲2*(n-1)的揹包,物品的體積是度數,可是這樣有可能會出現沒有被選的度數,那麼我們就先每個點都分配一個度,然後就是完全揹包啦



    #include<bits/stdc++.h>  
    using namespace std;  
    const int maxn = 25000;  
    int a[maxn];  
    int dp[maxn];  
    int main()  
    {  
        int T,n;  
        scanf("%d",&T);  
        while(T--)  
        {  
            scanf("%d",&n);  
            for(int i = 0;i<n-1;i++)  
                scanf("%d",&a[i]);  
            int V = 2*(n-1)-n;  
            for(int i = 0;i<=n;i++)  
                dp[i]=-1e9;  
            dp[0]=a[0]*n;  
            for(int i=1;i<n-1;i++)  
                a[i]-=a[0];  
            for(int i = 1;i<=V;i++)  
                for(int j = i;j<=V;j++)  
                    dp[j]=max(dp[j],dp[j-i]+a[i]);  
            printf("%d\n",dp[V]);  
        }  
        return 0;  
    }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章