This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#include<random>
#define ll long long
#define F first
#define S second
#define in insert
#define pb push_back
#define ppb pop_back()
#define d3 ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define cans cout << ans << "\n";
#define yes cout << "Yes" << "\n";
#define no cout << "No" << "\n";
#define pll pair<ll,ll>
#define lin cout << "\n";
#define sqr 340
#define mod 1000000007
#define mid ((l+r)/2)
#define lc (2*x)
#define rc (2*x+1)
#define sq 547
using namespace std;
ll n , s;
ll a[300009] , p[300009];
vector<ll> adj[300009];
ll vis[300009];
vector<pair<pll,ll>> o[300009];
set<pll> se;
set<pair<pll,ll>> sx;
void dfs(ll x , ll mn , ll sum , ll op)
{
sum+=a[x];
mn=min(mn,sum);
if(sum>=0)
{
o[op].pb({{mn,sum},x});
return;
}
for(auto it : adj[x])
dfs(it,mn,sum,op);
}
int main()
{
cin >> n >> s;
ll os = s;
for(int i = 1 ; n>=i ; i++)
{
cin >> a[i] >> p[i];
adj[p[i]].pb(i);
}
vector<ll> v;
for(int i = 1 ; n>=i ; i++)
{
if(p[i]==0)
v.pb(i);
}
while(true)
{
for(auto it : v)
dfs(it,0,0,it);
for(auto it : v)
{
for(auto itt : o[it])
{
if(-itt.F.F>s)
{
sx.in(itt);
}
else
{
se.in({itt.F.S,itt.S});
}
}
}
v.clear();
if(se.empty())
break;
auto itt = se.end();
itt--;
if(itt->F<0)
break;
s+=itt->F;
ll nd = itt->S;
se.erase(itt);
/*ll ln;
while(vis[nd]==0&&nd!=0)
{
ln=nd;
vis[nd]=1;
for(auto it : adj[nd])
{
p[it]=0;
if(vis[it]==0)
v.pb(it);
}
nd=p[nd];
}*/
if(!adj[nd].empty())
{
ll nod = adj[nd][0];
p[nod]=0;
v.pb(nod);
}
while(!sx.empty())
{
auto it = sx.end();
it--;
if(-it->F.F>s)
break;
se.in({it->F.S,it->S});
sx.erase(it);
}
/*for(auto itt : o[ln])
{
if(-itt.F.F>s)
{
sx.erase(itt);
}
else
{
se.erase({itt.F.S,itt.S});
}
}
o[ln].clear();*/
}
cout << s-os;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |