Happy Tree Friends(图论)

题目描述
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值