Submission #417070

#TimeUsernameProblemLanguageResultExecution timeMemory
417070errorgornWorst Reporter 4 (JOI21_worst_reporter4)C++17
100 / 100
739 ms194280 KiB
#include <bits/stdc++.h> using namespace std; #define ll long long #define ii pair<ll,ll> #define fi first #define se second #define endl '\n' #define puf push_front #define pof pop_front #define pub push_back #define pob pop_back #define lb lower_bound #define ub upper_bound #define rep(x,s,e) for (auto x=s-(s>e);x!=e-(s>e);(s<e?x++:x--)) #define all(x) (x).begin(),(x).end() #define sz(x) (int) (x).size() mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int n; int arr[200005]; int h[200005]; int c[200005]; vector<int> al[200005]; map<int,ll> s[200005]; void dfs(int i,int p){ for (auto &it:al[i]){ if (it==p) continue; dfs(it,i); if (sz(s[i])<sz(s[it])) swap(s[i],s[it]); for (auto &it2:s[it]) s[i][it2.fi]+=it2.se; } s[i][0]+=c[i]; s[i][h[i]+1]+=c[i]; s[i][h[i]]-=c[i]; auto iter=s[i].find(h[i]); while ((*iter).se<0){ ll temp=min((*prev(iter)).se,-(*iter).se); (*iter).se+=temp; if ((*prev(iter)).se==temp) s[i].erase(prev(iter)); else (*prev(iter)).se-=temp; } //cout<<i<<": "<<endl; //for (auto &it:s[i]) cout<<it.fi<<" "<<it.se<<endl; //cout<<endl; } bool vis[200005]; bool onstk[200005]; ll ans=0; void dfs_cyc(int i){ vis[i]=true; onstk[i]=true; if (!vis[arr[i]]) dfs_cyc(arr[i]); else if (onstk[arr[i]]){ vector<int> v; int curr=i; do{ v.pub(curr); curr=arr[curr]; } while (curr!=i); //for (auto &it:v) cout<<it<<" "; cout<<endl; map<int,ll> m; rep(x,0,sz(v)){ for (auto &it:al[v[(x+1)%sz(v)]]){ if (it==v[x]) continue; dfs(it,v[(x+1)%sz(v)]); for (auto &it2:s[it]) m[it2.fi]+=it2.se; } } ll tot=0; for (auto &it:v) tot+=c[it]; sort(all(v),[](int i,int j){ return h[i]>h[j]; }); ll best=tot+m[0]; while (!v.empty()){ int hh=h[v.back()]; ll save=0; while (!v.empty() && h[v.back()]==hh){ save+=c[v.back()]; v.pob(); } while (!m.empty() && (*m.begin()).fi<=hh){ tot+=(*m.begin()).se; m.erase(m.begin()); } best=min(best,tot-save); } ans+=best; } onstk[i]=false; } int main(){ cin.tie(0); cout.tie(0); cin.sync_with_stdio(false); cin>>n; rep(x,1,n+1) cin>>arr[x]>>h[x]>>c[x]; rep(x,1,n+1) al[arr[x]].pub(x); rep(x,1,n+1) if (!vis[x]) dfs_cyc(x); cout<<ans<<endl; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...