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>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef pair<int,int> pi;
typedef vector<pi> pii;
typedef tuple<int,int,int> tii;
typedef vector<ll> li;
typedef vector<li> lii;
#define REP(i,a,b) for(int i=a;i<b;i++)
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define LSOne(s) ((s)&(-s))
ll INF=1e18+10;
int inf=1e9+10;
ll M=1e9+7;
int n;
ll m;
vi p;
vector<ll> profit;
ll ans=0;
vi a;
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0);
cin>>n>>m;
p.resize(n);profit.resize(n);a.resize(n,-1);
REP(i,0,n){
ll x;int y;
cin>>x>>y;
p[i]=y;
if(y!=0)a[y-1]=i;
profit[i]=x;
}
if(m==1e18){
ll ans=0;
vector<vector<ll>> b(n);
for(int i=n-1;i>=0;i--){
if(b[i].empty()){
if(profit[i]>0){
ans+=profit[i];
if(p[i]!=0)b[p[i]-1].PB(profit[i]);
}
continue;
}
ll k=0;
for(auto u:b[i])k+=u;
if(profit[i]+k>0){
ans+=profit[i];
if(p[i]!=0)b[p[i]-1].PB(profit[i]+k);
}
else ans-=k;
}
cout<<ans;
return 0;
}
priority_queue<pair<ll,ll>> pq;
ll ans=0;
vi vis(n,0);vi sm(n,0);
REP(i,0,n){
if(vis[i])continue;
vis[i]=1;
if(profit[i]>0){
ans+=profit[i];
continue;
}
else{
ll y=0,z=0;
int x=i;
y+=profit[x];
x=a[x];
if(x!=-1)vis[x]=1;
while(x!=-1&&profit[x]<0){
y+=profit[x];
x=a[x];
if(x!=-1)vis[x]=1;
}
while(x!=-1&&profit[x]>0){
z+=profit[x];
x=a[x];
if(x!=-1)vis[x]=1;
}
if(y+z>0){
pq.push({y+sm[i],z});
continue;
}
if(x!=-1)sm[x]=y;
if(x!=-1)profit[x]+=y+z;
}
}
while(!pq.empty()){
ll y=pq.top().F;
ll z=pq.top().S;
pq.pop();
if(m>=y||ans>=y||ans+m>=y){
ans+=y+z;
}
else break;
}
cout<<ans;
return 0;
}
# | 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... |