题解:P10759 [BalticOI 2024] Jobs
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;
}