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

来源/分类

ICPC 2015 Changchun 

[提交] [状态]

比赛时看到这道题感觉是窒息的,但是赛后看题解更窒息,完全想不到是个背包,极其震惊

题意:给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;
}

猜你喜欢

转载自blog.csdn.net/renzijing/article/details/82932130