RXD has a tree
TT, with the size of
nn. Each edge has a cost.
Define f(S)f(S) as the the cost of the minimal Steiner Tree of the set SS on tree TT.
he wants to divide 2,3,4,5,6,…n2,3,4,5,6,…n into kk parts S1,S2,S3,…SkS1,S2,S3,…Sk,
where ⋃Si={2,3,…,n}⋃Si={2,3,…,n} and for all different i,ji,j , we can conclude that Si⋂Sj=∅Si⋂Sj=∅.
Then he calulates res=∑ki=1f({1}⋃Si)res=∑i=1kf({1}⋃Si).
He wants to maximize the resres.
1≤k≤n≤1061≤k≤n≤106
the cost of each edge∈[1,105]the cost of each edge∈[1,105]
SiSi might be empty.
f(S)f(S) means that you need to choose a couple of edges on the tree to make all the points in SS connected, and you need to minimize the sum of the cost of these edges. f(S)f(S) is equal to the minimal cost
InputThere are several test cases, please keep reading until EOF.
Define f(S)f(S) as the the cost of the minimal Steiner Tree of the set SS on tree TT.
he wants to divide 2,3,4,5,6,…n2,3,4,5,6,…n into kk parts S1,S2,S3,…SkS1,S2,S3,…Sk,
where ⋃Si={2,3,…,n}⋃Si={2,3,…,n} and for all different i,ji,j , we can conclude that Si⋂Sj=∅Si⋂Sj=∅.
Then he calulates res=∑ki=1f({1}⋃Si)res=∑i=1kf({1}⋃Si).
He wants to maximize the resres.
1≤k≤n≤1061≤k≤n≤106
the cost of each edge∈[1,105]the cost of each edge∈[1,105]
SiSi might be empty.
f(S)f(S) means that you need to choose a couple of edges on the tree to make all the points in SS connected, and you need to minimize the sum of the cost of these edges. f(S)f(S) is equal to the minimal cost
For each test case, the first line consists of 2 integer n,kn,k, which means the number of the tree nodes , and kk means the number of parts.
The next n−1n−1 lines consists of 2 integers, a,b,ca,b,c, means a tree edge (a,b)(a,b) with cost cc.
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≤100n≤100.OutputFor 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 6Sample Output
27
题意:将一颗树的2~n分成k块,求1到各块的最大权值
方法:由于每个点与它父节点的贡献为min(num[i],k),所以求出每个节点的子节点+1,并记录该节点的权值
#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=1000000+10;
int dist[N],num[N],head[N],cnt;
struct node
{
int v,next;
}edges[N];
void add(int u,int v,int w)
{
edges[cnt].v=v;
edges[cnt].next=head[u];
head[u]=cnt++;
}
void dfs(int u,int pre)
{
num[u]=1;
for(int i=head[u];i!=-1;i=edges[i].next)
{
int v=edges[i].v;
dfs(v,u);
num[u]+=num[v];
}
}
int main()
{
int n,k;
while(~scanf("%d%d",&n,&k))
{
cnt=0;
memset(head,-1,sizeof(head));
for(int i=1;i<n;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
dist[v]=w;
add(u,v,w);
}
dfs(1,0);
long long sum=0;
for(int i=2;i<=n;i++)
sum+=(long long)dist[i]*min(num[i],k);
printf("%lld\n",sum);
}
}