제출 #503826

#제출 시각아이디문제언어결과실행 시간메모리
503826tabrIslands (IOI08_islands)C++17
100 / 100
795 ms128400 KiB
#include <bits/stdc++.h> using namespace std; #ifdef tabr #include "library/debug.cpp" #else #define debug(...) #endif const int N = (int) 1e6; int l[N]; int nxt[N]; long long dist[N]; long long max_dist[N]; bool cycle[N]; bool was[N]; vector<int> g[N]; int p[N]; pair<int, long long> deq[N * 2]; int dsu_get(int x) { if (p[x] == x) { return x; } else { return p[x] = dsu_get(p[x]); } } bool dsu_unite(int x, int y) { x = dsu_get(x); y = dsu_get(y); if (x == y) { return false; } p[x] = y; return true; } int x[N]; int order[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; iota(p, p + n, 0); for (int i = 0; i < n; i++) { int j; cin >> j >> l[i]; j--; g[j].emplace_back(i); dsu_unite(i, j); nxt[i] = j; } long long ans = 0; for (int i = 0; i < n; i++) { if (i != dsu_get(i)) { continue; } int c = i; while (!was[c]) { was[c] = 1; c = nxt[c]; } int u = nxt[c]; cycle[c] = 1; int sz = 1; x[0] = c; while (u != c) { cycle[u] = 1; x[sz++] = u; u = nxt[u]; } int sz2 = 0; int beg = 0; int end = 0; for (int jj = 0; jj < sz; jj++) { int j = x[jj]; deq[end++].first = j; while (beg < end) { int v = deq[beg++].first; order[sz2++] = v; for (int to : g[v]) { if (cycle[to]) { continue; } dist[to] = dist[v] + l[to]; deq[end++].first = to; } } } long long t = 0; for (int j = sz2 - 1; j >= 0; j--) { int v = order[j]; max_dist[v] = max(max_dist[v], dist[v]); if (cycle[v]) { continue; } int to = nxt[v]; t = max(t, max_dist[to] + max_dist[v] - dist[to] * 2); max_dist[to] = max(max_dist[to], max_dist[v]); } long long y = l[c]; beg = end = 0; deq[end++] = make_pair(0, 0); for (int jj = 1; jj < sz * 2; jj++) { int j = jj % sz; if (x[deq[beg].first] == x[j]) { beg++; } t = max(t, y + max_dist[x[j]] - deq[beg].second); long long z = y - max_dist[x[j]]; while (beg < end && deq[end - 1].second >= z) { end--; } y += l[x[j]]; deq[end++] = make_pair(j, z); } ans += t; } cout << ans << '\n'; 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...