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
刚开始想法错了,看了别人得到吗才知道每次都可以不只连一条边,每次都可以像网一样覆盖下去,那么每一条边的贡献就是min(k,son[i]),就是k和它有多少儿子的最小值。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=1e6+5;
int fa[maxn];
int finds(int x)
{
return x==fa[x]?fa[x]:fa[x]=finds(fa[x]);
}
struct node
{
int fa,son,val;
bool operator< (const node& x)const
{
return val<x.val;
}
}a[maxn*2];
struct edge
{
int to,next,val;
}e[maxn*2];
int head[maxn],cnt;
void add(int x,int y,int val)
{
e[cnt].to=y;
e[cnt].next=head[x];
e[cnt].val=val;
head[x]=cnt++;
}
ll ans;
int n,k,son[maxn];
void dfs(int f,int ff,ll dis)
{
son[f]=1;
for(int i=head[f];~i;i=e[i].next)
{
int ne=e[i].to;
if(ne==ff)
continue;
dfs(ne,f,e[i].val);
son[f]+=son[ne];
}
ans+=(ll)dis*min(k,son[f]);
}
int vis[maxn];
int main()
{
while(~scanf("%d%d",&n,&k))
{
memset(head,-1,sizeof(head));
cnt=0;
for(int i=1;i<n;i++)
scanf("%d%d%d",&a[i].fa,&a[i].son,&a[i].val);
sort(a+1,a+n);
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<n;i++)
{
int fax=finds(a[i].fa);
int fay=finds(a[i].son);
if(fax!=fay)
fa[fay]=fax,add(a[i].fa,a[i].son,a[i].val),add(a[i].son,a[i].fa,a[i].val);
}
ans=0;
dfs(1,0,0);
printf("%lld\n",ans);
}
return 0;
}