This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> a(n), l(n);
for (int i = 0; i < n; i++) {
cin >> a[i] >> l[i];
--a[i];
assert(a[i] != i);
}
vector<vector<int>> g(n);
for (int i = 0; i < n; i++) {
g[i].push_back(a[i]);
g[a[i]].push_back(i);
}
vector<bool> was(n);
long long res = 0;
vector<long long> d(n, -1);
vector<vector<long long>> dp(n, vector<long long>(3));
for (int i = 0; i < n; i++) {
if (was[i]) {
continue;
}
vector<int> que(1, i);
for (int b = 0; b < (int) que.size(); b++) {
int x = que[b];
for (int y : g[x]) {
if (!was[y]) {
was[y] = true;
que.push_back(y);
}
}
}
for (int x : que) {
was[x] = false;
}
int x = i;
while (!was[x]) {
was[x] = true;
x = a[x];
}
int y = a[x];
vector<int> cyc(1, x);
while (y != x) {
cyc.push_back(y);
y = a[y];
}
for (int x : que) {
was[x] = true;
}
d[cyc[0]] = 0;
for (int i = 1; i < (int) cyc.size(); i++) {
int x = cyc[i - 1], y = cyc[i];
d[y] = d[x] + l[x];
}
function<void(int, int)> Solve = [&](int v, int pv) {
for (int u : g[v]) {
if (d[u] != -1 || u == pv) {
continue;
}
Solve(u, v);
dp[v][2] = max(dp[v][2], dp[v][1] + dp[u][1] + l[u]);
dp[v][1] = max(dp[v][1], dp[u][1] + l[u]);
}
};
long long c = 0;
for (int i : que) {
Solve(i, i);
c = max(c, dp[i][1]);
c = max(c, dp[i][2]);
}
vector<int> v;
for (int i : cyc) {
v.push_back(i);
}
for (int i : cyc) {
v.push_back(i);
}
long long t = d[cyc.back()] + l[cyc.back()];
int ptr = 0;
for (int i = 0; i < (int) cyc.size(); i++) {
for (int j = i + 1; j < (int) cyc.size(); j++) {
long long p = d[cyc[j]] - d[cyc[i]];
c = max(c, max(p, t - p) + dp[cyc[i]][1] + dp[cyc[j]][1]);
}
}
res += c;
}
cout << res << '\n';
return 0;
}
Compilation message (stderr)
islands.cpp: In function 'int main()':
islands.cpp:85:9: warning: unused variable 'ptr' [-Wunused-variable]
85 | int ptr = 0;
| ^~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |