题目描述
There is a Happy Tree on an island. Happy Tree consists of n apples linked by n-1 branches and the No.1 apple is the root of the tree. Each apple has a value a_i.
Today, k friends are playing under Happy Tree. Each of them can select only one apple, then gets the sum of the values from root to the selected apple, and take all the apples on the road (including the root and the selected apple). Of course, an apple can only be taken once.
Now, they want to know the maximum value they can get. They promise that everyone can select at least one apple.
输入
The first line consists of two non-negative integers, the number of apples n, and the number of friends k. ( 1 ≤ n ,k ≤2×105 )
The second line consists of n non-negative integers, the value of the i-th apple a_i. ( 1 ≤ a_i ≤ 109 )
Then there are n-1 lines, each line consists of two non-negative integers, and describe a branch between u and v. ( 1≤u ,v ≤n )
输出
Only one integer, the maximum value they can get.
样例输入
5 2
4 3 2 1 1
1 2
1 5
2 3
2 4
样例输出
10
思路
如图所示将树中每条较大链取出,放入优先队列中,前k条链的总和即为答案
代码实现
#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+10;
struct node
{
int to,nxt;
}G[N<<1];
int n,k,cnt;
int head[N<<1];
ll a[N];
priority_queue<ll>que;
void add(int u,int v)
{
G[++cnt].to=v;
G[cnt].nxt=head[u];
head[u]=cnt;
}
ll dfs(int x,int bf)
{
ll maxs=0;
for(int i=head[x];i;i=G[i].nxt)
{
int v=G[i].to;
if(v==bf) continue;
ll temp=dfs(v,x);
if(temp>maxs)
{
que.push(maxs);
maxs=temp;
}
else que.push(temp);
}
return maxs+a[x];
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);add(v,u);
}
ll ans=dfs(1,-1);
k--;
while(k-- && que.size())
{
ans+=que.top();
que.pop();
}
printf("%lld\n",ans);
return 0;
}