RXD and dividing
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)Total Submission(s): 1463 Accepted Submission(s): 632
Problem Description
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
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 .
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
解题思路:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
const int maxn=1e6+5;
struct node
{
int v,w;
};
vector <node> mp[maxn];
int sz[maxn],pre[maxn];
void dfs(int u, int fa)
{
sz[u] = 1;
for(int i = 0; i < mp[u].size(); i++)
{
int v = mp[u][i].v;
if(v == fa) continue;
pre[v] = mp[u][i].w;
dfs(v, u);
sz[u] += sz[v];
}
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
int u,w,v;
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&u,&v,&w);
mp[u].push_back((node){v,w});
mp[v].push_back((node){u,w});
}
dfs(1,-1);
long long ans=0;
for(int i=1;i<=n;i++)
{
ans+=1ll*pre[i]*min(sz[i],k);
}
printf("%lld\n",ans);
for(int i=1;i<=n;i++)
mp[i].clear();
}
return 0;
}