1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| #include <bits/stdc++.h> constexpr int MAXN = 1e6 + 6; using namespace std; using LL = long long; using Arr = LL[MAXN];
LL n, ans; Arr in, dis, diameter, belong, tmpDis, cycleDis; vector<pair<int, int> > G[MAXN];
inline void bfs(int cur, int cnt) { queue<int> q; q.push(cur); while (!q.empty()) { int cur = q.front(); q.pop(); belong[cur] = cnt; for (auto& e : G[cur]) { int to = e.first; if (!belong[to]) q.push(to); } } }
inline void topoSort() { queue<int> q; for (int i = 1; i <= n; i++) if (in[i] == 1) q.push(i); while (!q.empty()) { int cur = q.front(); q.pop(); for (auto& e : G[cur]) { int to = e.first, w = e.second; if (in[to] > 1) { in[to]--; diameter[belong[to]] = max(diameter[belong[to]], dis[to] + dis[cur] + w); dis[to] = max(dis[to], dis[cur] + w); if (in[to] == 1) q.push(to); } } } }
inline void dp(int cur, int cnt, LL res) { int st = cur, end = false, m(0); res = diameter[cnt]; do { end = true, in[cur] = 1; tmpDis[++m] = dis[cur]; for (auto& e : G[cur]) { int to = e.first, w = e.second; if (in[to] <= 1) continue; end = false, cur = to; cycleDis[m + 1] = cycleDis[m] + w; break; } } while (!end); for (auto& e : G[cur]) { int to = e.first, w = e.second; if (to == st) cycleDis[m + 1] = cycleDis[m] + w; } for (int i = 1; i < m; i++) { tmpDis[i + m] = tmpDis[i]; cycleDis[i + m] = cycleDis[m + 1] + cycleDis[i]; } deque<int> q; q.push_back(1); for (int i = 2; i < 2 * m; i++) { while (!q.empty() && i - q.front() >= m) q.pop_front(); res = max(res, tmpDis[i] + tmpDis[q.front()] + cycleDis[i] - cycleDis[q.front()]); while (!q.empty() && tmpDis[i] - cycleDis[i] >= tmpDis[q.back()] - cycleDis[q.back()]) q.pop_back(); q.push_back(i); } ans += res; }
int main() { std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n; for (int u = 1, v, w; u <= n; u++) { cin >> v >> w; G[u].emplace_back(make_pair(v, w)); G[v].emplace_back(make_pair(u, w)); in[u]++, in[v]++; } int cnt(0); for (int i = 1; i <= n; i++) if (!belong[i]) bfs(i, ++cnt); topoSort(); for (int i = 1; i <= n; i++) if (in[i] > 1) dp(i, belong[i], 0); cout << ans << endl; return 0; }
|