solution:
设 为:若进入以 为根的子树有正收益 ( 负收益定为 ),在考虑完能尽可能获取收益的结点后,进入的最低以 为根的子树最低收益门槛。
当我们在从下往上跑出 ,遍历 子树时,设 为当前收益(不包括起点 )。
1. 若 ,就可以不用继续拓展 。
2. 若 ,则要维护一个堆,存已扩展的子树中的 。
若堆顶的 代表我目前的 在 子树中拓展不动了,并且此时在 子树中收益仍为负,所以我就要更新进入 的门槛 ,并且 。
但我们发现,当我们在更新 时,会反复拓展相同子树。
所以思考发现:更新每一个 后,都会存在一个剩下的点堆 ,所以要遍历子树 时,可以直接跳过一大堆节点,并取 更新 。
因此还要定义一个 表示:从 拓展到边界 所赚得的收益,来维护 。
更新 时,我们可以将子树 合并入堆,再维护 ,这里很明显采用启发式合并,把小的塞入大的堆中,整体复杂度是 的。
PS: 新学了一个很好用的 pbds 可并堆,来进行启发式合并---教程。
感谢 @binbin_200811 的提醒,此题用 pbds 对配堆合并的时间复杂度为 ,可不用启发式合并。
code:
#include <bits/stdc++.h>
#include <bits/extc++.h>//pbds
#define inf 2e18
#define heap __gnu_pbds::priority_queue<int,cmp,__gnu_pbds::pairing_heap_tag>
typedef long long LL;//要开long long
typedef double D;
using namespace std;
const int SIZE=1e6+10,N=1e4+10;
LL id,T;
LL n,s;
LL val[SIZE];
int tot;
LL f[SIZE],earn[SIZE];
struct cmp
{
bool operator () (const int &A,const int &B)
{
return f[A]>f[B];
}
};
heap q[SIZE];
struct edge
{
int to,nxt,id;
}e[SIZE];
int h[SIZE],cnt;
void add(int u,int v,int id)
{
e[++cnt].to=v;
e[cnt].id=id;
e[cnt].nxt=h[u];
h[u]=cnt;
}
LL read()
{
LL res=0,x=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')x=-1;ch=getchar();}
while(isdigit(ch)){res=(res<<3)+(res<<1)+(ch^48);ch=getchar();}
return x*res;
}
void solve(int u)
{
LL now=0;
f[u]=0;
q[u].push(u);
while(!q[u].empty())
{
int cur=q[u].top();
q[u].pop();
if(f[cur]==inf) break;
if(now<f[cur])
{
f[u]+=f[cur]-now;
now=f[cur];
}
if(cur==u)
{
now+=val[u];
for(int i=h[cur];i;i=e[i].nxt)
{
int v=e[i].to;
q[u].push(v);
}
}
else
{
now+=earn[cur];
if(q[u].size()<q[cur].size()) q[u].swap(q[cur]);
q[u].join(q[cur]);
}
if(now>f[u])
{
earn[u]=now-f[u];
return ;
}
}
f[u]=inf;
}
void dfs(int u)
{
for(int i=h[u];i;i=e[i].nxt)
{
int v=e[i].to;
dfs(v);
}
solve(u);
}
void work(LL x)
{
LL now=s;
heap q1;
q1.push(0);
while(!q1.empty())
{
int u=q1.top();
q1.pop();
if(now<f[u]) break;
now+=val[u];
for(int i=h[u];i;i=e[i].nxt)
{
int v=e[i].to;
q1.push(v);
}
}
printf("%lld\n",now-x);
}
signed main()
{
n=read(),s=read();
for(int i=1;i<=n;i++)
{
val[i]=read();
int fa=read();
add(fa,i,++tot);
}
dfs(0);
work(s);
return 0;
}