제출 #103659

#제출 시각아이디문제언어결과실행 시간메모리
103659KCSCIslands (IOI08_islands)C++14
80 / 100
1397 ms132096 KiB
// 22.48 #include <bits/stdc++.h> using namespace std; const int DIM = 1000005; long long dst[DIM], dpl[DIM], dpr[DIM]; int oki[DIM], lev[DIM], cst[DIM], fth[DIM], cyc[DIM], val[DIM]; vector<pair<int, int>> edg[DIM]; int m; void dfs1(int x, int f) { oki[x] = true; lev[x] = lev[f] + 1; bool ok = false; for (auto it : edg[x]) { int y = it.first, c = it.second; if (!oki[y]) { cst[y] = c; fth[y] = x; dfs1(y, x); } else if (lev[y] < lev[x] and (y != f or ok)) { for (int z = x; z != fth[y]; z = fth[z]) { oki[z] = 2; cyc[m] = z; if (z == y) { val[m] = c; } else { val[m] = cst[z]; } ++m; } } if (y == f) { ok = true; } } } void dfs2(int x, int f, int &nd, long long &ds) { if (ds < dst[x]) { ds = dst[x]; nd = x; } for (auto it : edg[x]) { int y = it.first, c = it.second; if (oki[y] == 2 or y == f) { continue; } dst[y] = dst[x] + c; dfs2(y, x, nd, ds); } } int main(void) { #ifdef HOME freopen("islands.in", "r", stdin); freopen("islands.out", "w", stdout); #endif int n; cin >> n; for (int i = 1; i <= n; ++i) { int y, c; cin >> y >> c; edg[i].push_back(make_pair(y, c)); edg[y].push_back(make_pair(i, c)); } long long ans = 0; for (int k = 1; k <= n; ++k) { if (oki[k]) { continue; } m = 0; dfs1(k, 0); long long aux = 0; dpl[0] = 0; for (int i = 1; i < m; ++i) { dpl[i] = dpl[i - 1] + val[i - 1]; } dpr[m - 1] = val[m - 1]; for (int i = m - 2; i >= 0; --i) { dpr[i] = dpr[i + 1] + val[i]; } long long cs1 = -1LL << 60, cs2 = -1LL << 60; for (int i = 0; i < m; ++i) { int x = cyc[i]; oki[x] = 1; int c1; long long mx1 = -1; dst[x] = 0; dfs2(x, 0, c1, mx1); int c2; long long mx2 = -1; dst[c1] = 0; dfs2(c1, 0, c2, mx2); aux = max(aux, mx2); oki[x] = 2; if (i) { aux = max(aux, cs1 + dpl[i] + mx1); aux = max(aux, cs2 + dpr[i] + mx1); } cs1 = max(cs1, mx1 - dpl[i]); cs2 = max(cs2, mx1 + dpl[i]); } ans += aux; } cout << ans << endl; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...