题目链接 BZOJ 3252: 攻略
给出一棵有方向的树,求从根结点往下走K次能取得的最大权值,走过一次之后再走不会再取得贡献了。
用了长链剖分的思想,我们将长链的“长”理解为权值之和的长,然后将所有的长链存进一个堆内,每次取的都是最大值,取K次,或者是堆为空。
5 2
4 3 2 1 1
1 2
1 5
2 3
2 4
ans:10
8 3
1 2 3 1 4 2 1 1
1 2
1 3
2 4
2 5
4 8
3 6
3 7
ans:14
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define Big_INF 0x3f3f3f3f3f3f3f3f
#define eps 1e-6
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 2e5 + 7;
int N, K, head[maxN], cnt;
ll a[maxN];
struct Eddge
{
int nex, to;
Eddge(int a=-1, int b=0):nex(a), to(b) {}
} edge[maxN];
inline void addEddge(int u, int v)
{
edge[cnt] = Eddge(head[u], v);
head[u] = cnt++;
}
struct heap
{
priority_queue<ll> Que, Del;
inline ll top()
{
while(!Del.empty() && !Que.empty() && Que.top() == Del.top()) { Que.pop(); Del.pop(); }
return Que.top();
}
inline bool empty()
{
while(!Del.empty() && !Que.empty() && Que.top() == Del.top()) { Que.pop(); Del.pop(); }
return Que.empty();
}
inline void push(ll val) { Que.push(val); }
inline void clear(ll val) { Del.push(val); }
inline int size() { return (int)(Que.size() - Del.size()); }
inline void pop()
{
while(!Del.empty() && !Que.empty() && Que.top() == Del.top()) { Que.pop(); Del.pop(); }
Que.pop();
}
} st;
ll dp[maxN];
void dfs(int u)
{
dp[u] = 0;
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].to;
dfs(v);
if(dp[v] + a[v] > dp[u])
{
if(dp[u]) st.push(dp[u]);
dp[u] = dp[v] + a[v];
}
else st.push(dp[v] + a[v]);
}
if(u == 1) st.push(dp[1] + a[1]);
}
inline void init()
{
cnt = 0;
for(int i=1; i<=N; i++) head[i] = -1;
}
int main()
{
scanf("%d%d", &N, &K);
for(int i=1; i<=N; i++) scanf("%lld", &a[i]);
init();
for(int i=1, u, v; i<N; i++)
{
scanf("%d%d", &u, &v);
addEddge(u, v);
}
dfs(1);
ll ans = 0;
while((K--) && !st.empty())
{
ans += st.top();
st.pop();
}
printf("%lld\n", ans);
return 0;
}