Partial TreeTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 2087 Accepted Submission(s): 1035 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.
Input The first line contains an integer T indicating the total number of test cases.
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 | We have carefully selected several similar problems for you: 6447 6446 6445 6444 6443
|
思路:刚开始一看就以为是树形DP,想着凉了。后来仔细思考了一下,看着像是背包。
对于一张图G,n个结点,n-1条边,则各个结点的度的和 sum = (n-1) * 2;这里,sum 就相当于背包的容量 V 。各个点的度和权值就相当于物品的体积和价值。我们这样就把问题转化成了一个完全背包。
但是,如果直接变成一个完全背包的话是错误的,因为有些结点可能没有选(这样就不能构成一棵树了)。
所以我们进行一波骚操作:
把所有点的度初始都设定为a[1],初始的权值和为 a[1]*n(即dp[0])。
这样,我们之后只要使得度数之和变成(n-2)即可。
dp[i]表示度数为 i 条件下的最大收益。
状态转移方程:dp[i] = max( dp[i-k] + a[k+1] - a[1] )。意思是,我们想要更新度数为i的最大权值,我们会想着它可以基于之前的一个度数,然后把一个未扩展的子节点扩展a[k+1]-a[1]的权值。
-
我们有n个点可以扩展度数,而可能扩展的总度数只有n-2,所以一定不会出现多次扩展的情况
-
每个点都有一个为1的基准度,一定有办法把它们恰好拼成一棵树。
#pragma GCC optimize(2)
#include <bits/stdc++.h>
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define line cout<<"-----------------"<<endl;
typedef long long ll;
const int maxn = 1e5+10;
const int MAXN = 1e6+10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int N = 3010;
int n;
int dp[N],a[N],d[N];
int main(){
int T;
scanf("%d", &T);
while(T--){
clr(dp);clr(a);clr(d);
scanf("%d", &n);
for(int i=1;i<n;i++) scanf("%d", &a[i]);
for(int i=1;i<n;i++) d[i-1] = a[i] - a[1];
dp[0] = n * a[1];
int V = n - 2;
for(int i=1; i<=V; i++)
for(int j=1; j<=i; j++)
dp[i] = max(dp[i], dp[i-j]+d[j]);
printf("%d\n", dp[V]);
}
return 0;
}