#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define vi vector<int>
#define pi pair<int,int>
#define sz(v) (int)(v).size()
#define all(v) (v).begin(), (v).end()
#define compact(v) (v).erase(unique(all(v)), (v).end())
template<class T> using upq = priority_queue<T, vector<T>, greater<T>>;
template<class T> int lwrbound(const vector<T>& a, const T& b, const int s = 0){return int(lower_bound(s + all(a), b) - a.begin());}
template<class T> int uprbound(const vector<T>& a, const T& b, const int s = 0){return int(upper_bound(s + all(a), b) - a.begin());}
#define FOR(i, a, b) for(int i = (a); i <= (b); i++)
#define ROF(i, a, b) for(int i = (a); i >= (b); i--)
#define sumof(x) accumulate(all(x), 0ll)
#define dbg(x) "[" << #x " = " << (x) << "]"
#define el "\n"
using ll = long long;
using ld = long double;
template<class T> bool ckmx(T& a, const T b){return (a < b ? a = b, true : false);}
template<class T> bool ckmn(T& a, const T b){return (a > b ? a = b, true : false);}
const ll INF = 1e15;
void Main()
{
int N; cin >> N;
vector<ll> nxt(N + 1), w(N + 1);
FOR(i, 1, N){
cin >> nxt[i] >> w[i];
}
vi vis(N + 1), cycle(N + 1);
FOR(i, 1, N) if(!vis[i]){
int x = i;
for(; !vis[x]; x = nxt[x]){
vis[x] = i;
}
if(vis[x] == i){
cycle[x] = 1; int sz = 1;
for(int v = nxt[x]; v != x; v = nxt[v]){
cycle[v] = 1, ++sz;
}
if(sz == N){
cout << "0\n";
return;
}
}
}
vector<ll> Mx(N + 1), MxNC(N + 1);
FOR(i, 1, N){
ckmx(Mx[nxt[i]], w[i]);
if(!cycle[i]){
ckmx(MxNC[nxt[i]], w[i]);
}
}
ll ans = sumof(Mx);
FOR(i, 1, N) if(cycle[i]){
ll upd = -INF;
for(int x = nxt[i]; x != i; x = nxt[x]){
ckmx(upd, -Mx[x] + MxNC[x]);
cycle[x] = 0;
}
ckmx(upd, -Mx[i] + MxNC[i]);
ans += upd;
}
cout << sumof(w) - ans << el;
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
#define name "InvMOD"
if(fopen(name".INP", "r")){
freopen(name".INP", "r", stdin);
freopen(name".OUT", "w", stdout);
}
int t = 1; while(t--) Main();
return 0;
}
Compilation message (stderr)
telegraph.cpp: In function 'int32_t main()':
telegraph.cpp:92:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
92 | freopen(name".INP", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
telegraph.cpp:93:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
93 | freopen(name".OUT", "w", stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~| # | 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... |