Submission #503783

#TimeUsernameProblemLanguageResultExecution timeMemory
503783tabrIslands (IOI08_islands)C++17
67 / 100
459 ms131076 KiB
#include <bits/stdc++.h> using namespace std; #ifdef tabr #include "library/debug.cpp" #else #define debug(...) #endif struct dsu { vector<int> p; vector<int> sz; int n; dsu(int _n) : n(_n) { p.resize(n); iota(p.begin(), p.end(), 0); sz.assign(n, 1); } inline int get(int x) { if (p[x] == x) { return x; } else { return p[x] = get(p[x]); } } inline bool unite(int x, int y) { x = get(x); y = get(y); if (x == y) { return false; } if (sz[x] > sz[y]) { swap(x, y); } p[x] = y; sz[y] += sz[x]; return true; } inline bool same(int x, int y) { return (get(x) == get(y)); } }; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<vector<int>> g(n); vector<int> l(n); vector<int> e(n); dsu uf(n); for (int i = 0; i < n; i++) { int j; cin >> j >> l[i]; j--; uf.unite(i, j); e[i] = j; g[i].emplace_back(i); g[j].emplace_back(i); } for (int i = 0; i < n; i++) { if (e[e[i]] == i) { l[e[i]] = l[i] = max(l[e[i]], l[i]); } } vector<vector<int>> vs(n); for (int i = 0; i < n; i++) { vs[uf.get(i)].emplace_back(i); } long long ans = 0; vector<long long> mx(n); vector<int> cycle(n); vector<int> was(n); for (int i = 0; i < n; i++) { if (i != uf.get(i)) { continue; } int c = i; while (!was[c]) { was[c] = 1; c = e[c]; } cycle[c] = 1; int u = e[c]; while (u != c) { cycle[u] = 1; u = e[u]; } queue<int> que; for (int j : vs[i]) { if (g[j].size() == 1) { que.emplace(j); } } long long t = 0; while (!que.empty()) { int v = que.front(); que.pop(); int to = e[v]; t = max(t, mx[to] + mx[v] + l[v]); mx[to] = max(mx[to], mx[v] + l[v]); if (!cycle[to]) { que.emplace(to); } } vector<int> x; vector<long long> y; x.emplace_back(c); y.emplace_back(0); y.emplace_back(l[c]); u = e[c]; while (u != c) { x.emplace_back(u); y.emplace_back(y.back() + l[u]); u = e[u]; } u = e[c]; x.emplace_back(c); y.emplace_back(y.back() + l[c]); while (u != c) { x.emplace_back(u); y.emplace_back(y.back() + l[u]); u = e[u]; } deque<pair<int, long long>> deq; deq.emplace_back(0, 0); for (int j = 1; j < (int) x.size(); j++) { if (x[deq.front().first] == x[j]) { deq.pop_front(); } t = max(t, y[j] + mx[x[j]] - deq.front().second); long long z = y[j] - mx[x[j]]; while (!deq.empty() && deq.back().second >= z) { deq.pop_back(); } deq.emplace_back(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...