#include #include #include #include using namespace std; const int INF = (int)1e9 + 7; template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } struct StronglyConnectedComponents { vector> gg, rg; vector comp, order, seen; StronglyConnectedComponents(int v) : gg(v), rg(v), comp(v, -1), seen(v, 0) { } void add_edge(int x, int y) { gg[x].emplace_back(y); rg[y].emplace_back(x); } void dfs(int u) { seen[u] = true; for (int v: gg[u]) if (!seen[v]) dfs(v); order.emplace_back(u); } void rdfs(int u, int id) { comp[u] = id; for (int v: rg[u]) if (comp[v] == -1) rdfs(v, id); } vector> build() { for (int u = 0; u < gg.size(); ++u) if (!seen[u]) dfs(u); reverse(begin(order), end(order)); int id = 0; for (int u: order) if (comp[u] == -1) rdfs(u, id++); vector> g_comp(id); set> connect; for (int u = 0; u < gg.size(); ++u) for (int v: gg[u]) { int x = comp[u], y = comp[v]; if (x == y) continue; if (connect.count({x, y})) continue; g_comp[x].emplace_back(y); connect.emplace(x, y); } return g_comp; } int operator[](int k) { return comp[k]; } }; #include int main() { //cout << fixed << setprecision(1); int n; cin >> n; vector lv(n); StronglyConnectedComponents scc(n); double ans = 0; for (int i = 0; i < n; i++) { int s; cin >> lv[i] >> s; s--; ans += lv[i]; scc.add_edge(s, i); } ans /= 2; vector> dag = scc.build(); int sz = dag.size(); vector in_deg(sz); for (int u = 0; u < sz; u++) for (auto v: dag[u]) in_deg[v]++; vector mins(sz, INF); for (int i = 0; i < n; i++) if (in_deg[scc[i]] == 0) { chmin(mins[scc[i]], lv[i]); } for (int u = 0; u < sz; u++) if (mins[u] != INF) ans += 1.0 * mins[u] / 2; cout << ans << endl; return 0; }