hdu5534—Partial Tree(完全背包+思维,转化的超级巧妙哇~)

Partial Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 2179    Accepted Submission(s): 1086


 

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

 

2 3 2 1 4 5 1 4

 

 

Sample Output

 

5 19

 

 

Source

2015ACM/ICPC亚洲区长春站-重现赛(感谢东北师大)

 

 

Recommend

hujie

这道题目在健大佬的帮助下终于搞明白了~(泪流满面......)

思路:

这道题的思路就是转化成完全背包的思想。

因为一共是2*n-2个度,而且确定的一点是每一个点都至少有1个度。

这样子还剩下n-2个度。问题就转化成了n-2个度分给n个点(每个点拥有的度数可以是0).。

然后想到这我的思路就不大明晰了,就是不知该怎么想了。这样继续想的话就卡掉了。

 

但是题目给了n-1个f(i)意思就是说,有n-1种物品,每一种物品的种类都是无限的(因为每个点的度数是可以相同的),并且每件物品的价值都是v【i】,并且每件物品的体积(重量)都是i(就是这个物品的度数),然后把这几种物品,正好装入一个容量为n-2的背包里。

嗯!想到这里就觉得差不多了吧。完全跟树没关系了。就是装就行了,保证了每个点一定是有物品的。

但是这道题还有个坑,就是我们默认了每个点都有了一个度了,所以实际上我们在枚举物品的时候,他们的度都是i+1(假设从1开始循环)

然后背包就好了

代码:

#include
using namespace std;
const int maxn=2018;
const int inf=0x3f3f3f3f;
int v[maxn],dp[maxn];
int main()
{
    int t,n,ans;
    scanf("%d",&t);
    while(t--){
        ans=0;
        scanf("%d",&n);
        for(int i=1;i<=n-1;i++){
            scanf("%d",&v[i]);
        }
        memset(dp,-inf,sizeof(dp));
        dp[0]=0;
        for(int i=1;i<=n-1;i++){///一共n-1个物品.每一个物品的价值是v[i+1],每一个物品的体积是i
            for(int j=i;j<=n-2;j++){///背包的容量
                ///if(j>=i)
                dp[j]=max(dp[j],dp[j-i]+v[i+1]-v[1]);
            }
        }
        ans=dp[n-2]+n*v[1];
        printf("%d\n",ans);
    }
    return 0;
}

 

你可能感兴趣的:(背包)