제출 #852809

#제출 시각아이디문제언어결과실행 시간메모리
852809lorenzoferrariIslands (IOI08_islands)C++17
90 / 100
1233 ms131072 KiB
#include "bits/stdc++.h" using namespace std; using LL = long long; static constexpr int N = 1e6+5; vector<array<int, 2>> edges; vector<vector<int>> adj; vector<array<int, 2>> par; bitset<N> vis, cyc; int cycle_node = -1; int back_edge = -1; void dfs(int v, int pi) { vis[v] = true; for (auto i : adj[v]) { auto [uv, w] = edges[i]; int u = uv^v; if (i == pi) continue; // deal with cycles of length 2 if (!vis[u]) { par[u] = {v, w}; dfs(u, i); } else if (vis[u] && cycle_node == -1) { cycle_node = v; par[u] = {v, w}; back_edge = i; } } } void find_diam(int v, int p, LL dist, array<LL, 2>& max_dist) { max_dist = max(max_dist, array<LL, 2>{dist, v}); for (auto i : adj[v]) { auto [uv, w] = edges[i]; int u = uv^v; if (u == p || i == back_edge) continue; find_diam(u, v, dist + w, max_dist); } } LL height(int v, int p) { LL ans = 0; for (auto i : adj[v]) { auto [uv, w] = edges[i]; int u = uv^v; if (u == p || i == back_edge) continue; if (cyc[u]) continue; ans = max(ans, w + height(u, v)); } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; adj.resize(n+1); par.resize(n+1); edges.resize(n+1); for (int v = 1, u, w; v <= n; ++v) { cin >> u >> w; edges[v] = {u^v, w}; adj[v].push_back(v); adj[u].push_back(v); } LL ans = 0; for (int v = 1; v <= n; ++v) { if (!vis[v]) { // first dfs dfs(v, -1); // diameter array<LL, 2> max_dist{0, v}; find_diam(v, -1, 0, max_dist); int u = max_dist[1]; max_dist = {0, u}; find_diam(u, -1, 0, max_dist); LL diameter = max_dist[0]; // path traversing the cycle LL a = cycle_node; LL cycle_length = 0; while (par[a][0] != cycle_node) { cyc[a] = true; cycle_length += par[a][1]; a = par[a][0]; } cyc[a] = true; cycle_length += par[a][1]; a = cycle_node; LL max1 = -1e9, max2 = -1e9; LL prv1 = height(a, -1); LL prv2 = prv1; while (par[a][0] != cycle_node) { auto [b, w] = par[a]; prv1 += w; prv2 -= w; LL h = height(b, -1); max1 = max(max1, prv1 + h); max2 = max(max2, prv2 + h); prv1 = max(prv1, h); prv2 = max(prv2, h); a = b; } LL cycle_path = max(max1, cycle_length + max2); // increase the answer by the maximum path in the current cc ans += max(diameter, cycle_path); cycle_node = -1; // reset back_edge = -1; } } cout << ans << "\n"; }
#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...