题解:P10759 [BalticOI 2024] Jobs

· · 题解

solution:

设 f[u] 为:若进入以 u 为根的子树有正收益 ( 负收益定为 \inf ),在考虑完能尽可能获取收益的结点后,进入的最低以 u 为根的子树最低收益门槛。

当我们在从下往上跑出 f[u],遍历 u 子树时,设 now 为当前收益(不包括起点 0)。

1. 若 now \ge f[u],就可以不用继续拓展 f[u]。

2. 若 now < f[u],则要维护一个堆,存已扩展的子树中的 f[v]。

若堆顶的 f[top] > now 代表我目前的 now 在 u 子树中拓展不动了,并且此时在 u 子树中收益仍为负,所以我就要更新进入 u 的门槛 f[u]=f[u]+f[top]-now,并且 now=f[top]。

但我们发现,当我们在更新 f[u] 时,会反复拓展相同子树。

所以思考发现:更新每一个 f[cur] 后,都会存在一个剩下的点堆 Q _ {cur},所以要遍历子树 cur 时,可以直接跳过一大堆节点,并取 Q _ {cur} 更新 f。

因此还要定义一个 earn[cur] 表示:从 cur 拓展到边界 Q _ {cur} 所赚得的收益,来维护 now。

更新 u 时,我们可以将子树 Q 合并入堆,再维护 now,这里很明显采用启发式合并,把小的塞入大的堆中,整体复杂度是 O(n\log^2n) 的。

PS: 新学了一个很好用的 pbds 可并堆,来进行启发式合并---教程。

感谢 @binbin_200811 的提醒,此题用 pbds 对配堆合并的时间复杂度为 O(1),可不用启发式合并。

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;
}