题目描述:
忍者的上下级关系构成一棵树,每个忍者有两个值:薪水和领导力。
给一个预算m,要你选择一个忍者作为管理者,并雇佣他的子树中的一些忍者(他自己雇不雇佣都可以),在这些忍者的薪水之和<=m的前提下,让雇佣的忍者数乘以管理者的领导力最大。
题目分析:
枚举每一个忍者作为管理者,看子树中最多能选几个忍者。
显然需要合并儿子的信息。
我一开始想的用权值线段树合并,查询的时候就在线段树上二分。
然后看题解说用可并堆,维护一个大根堆,如果当前堆中的薪水总和>m就把堆顶弹出。每个点只会被弹出一次,所以是nlogn的。
(%题解。。)
然后就上左偏树了。
Code:
#include<cstdio>
#include<cctype>
#include<algorithm>
#define maxn 100005
#define LL long long
using namespace std;
char cb[1<<15],*cs,*ct;
#define getc() (cs==ct&&(ct=(cs=cb)+fread(cb,1,1<<15,stdin),cs==ct)?0:*cs++)
inline void read(int &a){
char c;while(!isdigit(c=getc()));
for(a=c-'0';isdigit(c=getc());a=a*10+c-'0');
}
struct node{
int l,r,v,d,siz;
LL sum;
}t[maxn];
int n,m,a[maxn],id[maxn];
LL ans;
int fir[maxn],nxt[maxn],to[maxn],tot;
inline void line(int x,int y){nxt[++tot]=fir[x];fir[x]=tot;to[tot]=y;}
inline void upd(int x){
if(t[t[x].l].d<t[t[x].r].d) swap(t[x].l,t[x].r);
t[x].siz=t[t[x].l].siz+t[t[x].r].siz+1;
t[x].sum=t[t[x].l].sum+t[t[x].r].sum+t[x].v;
t[x].d=t[t[x].r].d+1;
}
int merge(int x,int y){
if(!x||!y) return x+y;
if(t[x].v<t[y].v) swap(x,y);
t[x].r=merge(t[x].r,y);
upd(x);
return x;
}
void dfs(int u){
id[u]=u,upd(u);
for(int i=fir[u],v;i;i=nxt[i]){
dfs(v=to[i]);
id[u]=merge(id[u],id[v]);
while(t[id[u]].sum>m) id[u]=merge(t[id[u]].l,t[id[u]].r);
}
ans=max(ans,1ll*t[id[u]].siz*a[u]);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("H.in","r",stdin);
#endif
t[0].d=-1;
read(n),read(m);
for(int i=1,x;i<=n;i++) {read(x),read(t[i].v),read(a[i]);if(x) line(x,i);}
dfs(1);
printf("%lld",ans);
}