#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
#define ll long long
#define pb push_back
#define all(x) x.begin(), x.end()
const int mod = 1000000007;
const int N = 1000005;
ll a[N+2], dp[N+2], mx[N+2], val[N+2], d[N+2];
bool vis[N+2];
map<ll, map<ll, ll>> adj;
vector<array<ll, 2>> leafs;
vector<ll> cmp;
ll mxdep = 0;
void dfs(int n, ll cost = 0, ll dep = 0){
vis[n] = 1;
mxdep = max(dep, mxdep);
d[n] = dep;
cmp.pb(n);
for(auto[i, j] : adj[n]){
if(!vis[i]){
dfs(i, j, dep + 1);
val[i] = max(val[i], val[n] + j);
}
}
}
void solve(){
ll n;
cin>>n;
for(int i = 1; i <= n; i++){
ll u, v;
cin>>u>>v;
adj[i][u] = max(adj[i][u], v);
adj[u][i] = max(adj[u][i], v);
mx[i] = max(mx[i], v);
mx[u] = max(mx[u], v);
}
auto find_cost = [&](ll n){
queue<array<ll, 2>> q;
q.push({n, 0});
ll mx233 = 0;
while(!q.empty()){
auto cur = q.front();
vis[cur[0]] = 1;
q.pop();
array<ll, 2> curmx = {0, 0};
mx233 = max(mx233, cur[1]);
for(auto [i, j] : adj[cur[0]]){
if(j > curmx[1] && !vis[i]){
curmx[0] = i;
curmx[1] = j;
}
}
if(!curmx[0])break;
q.push({curmx[0], cur[1] + curmx[1]});
}
return mx233;
};
ll ans = 0;
for(int i = 1; i <= n; i++){
if(!vis[i]){
dfs(i);
for(auto j : cmp){
if(mxdep == d[j]){
leafs.pb({val[j], j});
}
vis[j] = 0;
}
sort(all(leafs));
reverse(all(leafs));
ans += find_cost(leafs[0][1]);
for(auto j : cmp)vis[j] = 1;
leafs.clear();
cmp.clear();
mxdep = 0;
}
}
cout<<ans;
}
int main(){
cin.tie(0)->sync_with_stdio(0);
int tt = 1;
//cin>>tt;
while(tt--){
solve();
cout<<'\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... |
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |