#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; struct Node { int i; double L; Node(int i = -1, double L = -1) { this->i = i; this->L = L; } bool operator>(const Node &n) const { return L > n.L; } }; typedef vector > Graph; // 強連結成分分解ライブラリ class StronglyConnectedComponent { public: Graph G; Graph rG; Graph cG; vector vs; vector used; vector componentId; int componentCount; int V; StronglyConnectedComponent(int V) { this->V = V; used = vector(V); componentId = vector(V); G = Graph(V); rG = Graph(V); } void add_edge(int from, int to) { assert(0 <= from < V); assert(0 <= to < V); G[from].push_back(to); rG[to].push_back(from); } void run() { fill(used.begin(), used.end(), false); componentCount = 0; vs.clear(); for (int v = 0; v < V; ++v) { if (used[v]) continue; dfs(v); } fill(used.begin(), used.end(), false); for (int i = vs.size() - 1; i >= 0; --i) { int v = vs[i]; if (used[v]) continue; cG.push_back(vector()); rdfs(v, componentCount++); } } private: void dfs(int v) { used[v] = true; for (int i = 0; i < G[v].size(); ++i) { int u = G[v][i]; if (used[u]) continue; dfs(u); } vs.push_back(v); } void rdfs(int v, int k) { used[v] = true; componentId[v] = k; cG[k].push_back(v); for (int i = 0; i < rG[v].size(); ++i) { int u = rG[v][i]; if (used[u]) continue; rdfs(u, k); } } }; vector tsort(Graph G, int start, int end) { vector ret; int degree[end]; memset(degree, 0, sizeof(degree)); for (int from = start; from < end; from++) { for (int i = 0; i < G[from].size(); i++) { int to = G[from][i]; degree[to]++; } } stack root; for (int i = start; i < end; i++) { if (degree[i] == 0) { root.push(i); } } while (!root.empty()) { int from = root.top(); root.pop(); ret.push_back(from); for (int i = 0; i < G[from].size(); i++) { int to = G[from][i]; degree[to]--; if (degree[to] == 0) { root.push(to); } } } return ret; } int main() { int N; cin >> N; StronglyConnectedComponent scc(N); vector E[N]; vector RE[N]; double L[N]; int S[N]; for (int i = 0; i < N; ++i) { cin >> L[i] >> S[i]; S[i]--; scc.add_edge(S[i], i); E[S[i]].push_back(i); } scc.run(); int cnt = scc.componentCount; double ans = 0.0; bool checked[N]; memset(checked, false, sizeof(checked)); Graph G(N); for (int i = 0; i < cnt; ++i) { vector T = scc.cG[i]; if (T.size() <= 1) { int v = T[0]; for (int u : E[v]) { if (u == v) continue; G[v].push_back(u); } continue; } double min_l = DBL_MAX; for (int v : T) { checked[v] = true; min_l = min(min_l, L[v] / 2.0); ans += L[v] / 2.0; } ans += min_l; } vector res = tsort(G, 0, N); for (int v : res) { if (checked[v]) continue; if (checked[S[v]]) { ans += L[v] / 2.0; } else { ans += L[v]; } checked[v] = true; } cout << fixed << setprecision(1) << ans << endl; return 0; }