#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; bool used[100]; int p[100]; int num = 0; vector> good; vector> bad; int level[100]; void dfs(int s){ used[s] = true; for(auto v : good[s]) { if (used[v])continue; dfs(v); } p[num++] = s; } int bfs(int s){ int res = level[s]; int mini = res; int cnt = 1; queue que; que.push(s); used[s] = true; if (bad[s].size() == 0)return level[s] * 2; while (que.empty() == false){ auto v = que.front(); que.pop(); //cout << v << " "; for(auto u :bad[v]) { if (used[u])continue; used[u] = true; que.push(u); res += level[u]; mini = min(mini, level[u]); cnt++; } } if (cnt > 1)res += mini; // cout << endl; return res; } int main(void){ int N,s,sum=0; cin >> N; good.resize(N); bad.resize(N); for (int i = 0; i < N; i++) { used[i] = false; cin >> level[i] >> s; s--; if (s != i){ good[s].push_back(i); bad[i].push_back(s); } } for (int i = 0; i < N; i++) { if (used[i])continue; dfs(i); } reverse(p, p + N); for (int i = 0; i < N; i++) { used[i] = false; // cout << p[i] << " "; } //cout << endl; for (int i = 0; i < N; i++) { if (used[p[i]])continue; sum += bfs(p[i]); } cout << sum / 2.0 << endl; return 0; }