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;
#define FAST ios_base::sync_with_stdio(false); cin.tie(0);
#define pb push_back
#define eb emplace_back
#define ins insert
#define f first
#define s second
#define cbr cerr<<"hi\n"
#define mmst(x, v) memset((x), v, sizeof ((x)))
#define siz(x) ll(x.size())
#define all(x) (x).begin(), (x).end()
#define lbd(x,y) (lower_bound(all(x),y)-x.begin())
#define ubd(x,y) (upper_bound(all(x),y)-x.begin())
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
inline long long rand(long long x, long long y) { return rng() % (y+1-x) + x; } //inclusive
string inline to_string(char c) {string s(1,c);return s;} template<typename T> inline T gcd(T a,T b){ return a==0?llabs(b):gcd(b%a,a); }
using ll=long long;
using ld=long double;
#define FOR(i,s,e) for(ll i=s;i<=ll(e);++i)
#define DEC(i,s,e) for(ll i=s;i>=ll(e);--i)
using pi=pair<ll,ll>; using spi=pair<ll,pi>; using dpi=pair<pi,pi>; 
long long LLINF = 1e18;
int INF = 1e9+1e6;
#define MAXN (200006)
ll n, mx, P[MAXN], A[MAXN], C[MAXN], ans, point[MAXN];
bitset<MAXN> vis, inc;
vector<int> stk, cy;
vector<int> v[MAXN];
void cycle(int x) {
	vis[x]=1;
	stk.eb(x);
	if(!vis[P[x]]) cycle(P[x]);
	else {
		while(1) {
			if(stk.empty()) {
				cy.clear();
				break;
			}
			ll y=stk.back(); stk.pop_back();
			cy.eb(y);
			if(y==P[x]) break;
		}
	}
}
map<ll,ll> *mp[MAXN];
void dfs(int x) {
	mp[x] = new map<ll,ll>;
	for(auto i:v[x]) {
		dfs(i);
		if(mp[x]->size() < mp[i]->size()) mp[x] = mp[i];
	}
	for(auto i:v[x]) if(mp[x] != mp[i]) {
		for(auto j:*mp[i]) (*mp[x])[j.f] += j.s;
	}
	(*mp[x])[mx] += C[x];
	(*mp[x])[A[x]] -= C[x];
	(*mp[x])[A[x]-1] += C[x];
	auto it = mp[x]->find(A[x]);
	while(it->s < 0) {
		auto tmp = next(it);
		assert(tmp != mp[x]->end());
		tmp->s += it->s;
		mp[x]->erase(it);
		it = tmp;
	}
	if(it->s == 0) mp[x]->erase(it);
}
int main() {
	FAST
	cin>>n;
	FOR(i,1,n) cin>>P[i]>>A[i]>>C[i];
	mx = *max_element(A+1, A+n+1) + 1;
	FOR(i,1,n) A[i] = mx - A[i];
	FOR(i,1,n) point[i]=i;
	FOR(i,1,n) if(!vis[i]) {
		stk.clear(), cy.clear();
		cycle(i);
		if(cy.size() <= 1) continue;
		sort(all(cy), [](int x,int y){return A[x]>A[y];});
		FOR(i,0,siz(cy)-2) {
			P[cy[i]] = cy[i+1];
		}
		P[cy.back()]=cy.back();
		for(auto i:cy) point[i]=cy[0], inc[i]=1;
	}
	FOR(i,1,n) if(!inc[i]) P[i] = point[P[i]];
	FOR(i,1,n) if(P[i] ^ i) v[P[i]].eb(i);
	FOR(i,1,n) if(P[i] == i) {
		dfs(i);
		ans += (*mp[i])[mx];
	}
	cout<<ans<<'\n';
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |