3252: 攻略
Time Limit: 10 Sec Memory Limit: 128 MB[ Submit][ Status][ Discuss]
Description
题目简述:树版[k取方格数]
众所周知,桂木桂马是攻略之神,开启攻略之神模式后,他可以同时攻略k部游戏。
今天他得到了一款新游戏《XX半岛》,这款游戏有n个场景(scene),某些场景可以通过不同的选择支到达其他场景。所有场景和选择支构成树状结构:开始游戏时在根节点(共通线),叶子节点为结局。每个场景有一个价值,现在桂马开启攻略之神模式,同时攻略k次该游戏,问他观赏到的场景的价值和最大是多少(同一场景观看多次是不能重复得到价值的)
“为什么你还没玩就知道每个场景的价值呢?”
“我已经看到结局了。”
Input
第一行两个正整数n,k
第二行n个正整数,表示每个场景的价值
以下n-1行,每行2个整数a,b,表示a场景有个选择支通向b场景(即a是b的父亲)
保证场景1为根节点
Output
输出一个整数表示答案
Sample Input
5 2
4 3 2 1 1
1 2
1 5
2 3
2 4
4 3 2 1 1
1 2
1 5
2 3
2 4
Sample Output
10
HINT
对于100%的数据,n<=200000,1<=场景价值<=2^31-1
Source
好巧妙的做法,维护每一个节点的最大链,每次删掉一条链上的节点就行了,用堆维护
考试时暴力60分
#include<ext/pb_ds/priority_queue.hpp>
#include<bits/stdc++.h>
#define pa pair<long long,int>
using namespace std;
const int N = 200000 + 5;
int n,k,v[N],last[N],cnt; long long mx[N],ans;
struct Edge{ int to,next; }e[N*2];
void insert( int u, int v ){ e[++cnt].to = v; e[cnt].next = last[u]; last[u] = cnt; }
__gnu_pbds::priority_queue< pa > :: point_iterator id[N];
__gnu_pbds::priority_queue< pa > q;
void dfs( int x ){
for( int i = last[x]; i; i = e[i].next )
dfs( e[i].to ), mx[x] = max( mx[x], mx[e[i].to] );
mx[x] += v[x]; id[x] = q.push( make_pair(mx[x],x) );
}
void del( int x ){
q.erase(id[x]);
for( int i = last[x]; i; i = e[i].next )
if( mx[x] == mx[e[i].to] + v[x] )
{ del( e[i].to ); break; }
}
int main(){
cin>>n>>k;
for( int i = 1; i <= n; i++ ) scanf("%d", &v[i]);
for( int i = 1,u,v; i < n; i++ ){
scanf("%d%d", &u, &v);
insert( u, v );
}
dfs(1);
for( int i = 1; i <= k && !q.empty(); i++ ){
int now = q.top().second; ans += mx[now]; del(now);
}
cout<<ans<<endl;
return 0;
}