URL : http://acm.hdu.edu.cn/showproblem.php?pid=6060
RXD has a tree T, with the size of n. Each edge has a cost.
Define f(S) as the the cost of the minimal Steiner Tree of the set S on tree T.
he wants to divide 2,3,4,5,6,…n into k parts S1,S2,S3,…Sk,
where ⋃Si={2,3,…,n} and for all different i,j , we can conclude that Si⋂Sj=∅.
Then he calulates
res=∑ki=1f({1}⋃Si)
.
He wants to maximize the res.
1≤k≤n≤106
the cost of each edge∈[1,105]
Si might be empty.
f(S) means that you need to choose a couple of edges on the tree to make all the points in S connected, and you need to minimize the sum of the cost of these edges. f(S) is equal to the minimal cost
Input
There are several test cases, please keep reading until EOF.
For each test case, the first line consists of 2 integer n,k, which means the number of the tree nodes , and k means the number of parts.
The next n−1 lines consists of 2 integers, a,b,c, means a tree edge (a,b) with cost c.
It is guaranteed that the edges would form a tree.
There are 4 big test cases and 50 small test cases.
small test case means n≤100.
Output
For each test case, output an integer, which means the answer.
Sample Input
5 4
1 2 3
2 3 4
2 4 5
2 5 6
Sample Output
27
题解
直接看代码应该就能懂了
既然要求最大值,就让边尽可能的多被使用
取1为根节点,若u -> v 有一条价值为c的边,设以节点v为根节点的子树节点个数为d(v)
那么边(u,v)最多使用
min(d(v),k)
次,那么这条边的对答案的贡献就是
c⋅min(d(v),k)
#include<stdio.h>
#include<string.h>
typedef long long LL;
const int MAXN = 1e6 + 50;
struct node{int nxt, to, cost;} E[MAXN<<1];
int lnk[MAXN], tal, n, k;
LL ans;
inline void add(int x, int y, int c) {
E[tal].nxt = lnk[x];
E[tal].to = y;
E[tal].cost = c;
lnk[x] = tal++;
}
inline int min(int a, int b) {
return a < b ? a : b;
}
inline int dfs(int u, int fa) {
int cnt = 1;
for(int i = lnk[u]; i; i = E[i].nxt) {
if(fa == E[i].to) continue;
int num = dfs(E[i].to, u);
ans += 1LL * min(num, k) * E[i].cost;
cnt += num;
}
return cnt;
}
int main()
{
while(scanf("%d%d", &n, &k) != EOF) {
tal = 1;
for(int i = 1; i < n; ++i) {
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
add(x, y, c);
add(y, x, c);
}
ans = 0;
dfs(1, 1);
printf("%lld\n", ans);
memset(lnk, 0, sizeof(int) * (n + 2));
}
return 0;
}