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>
#define pii pair<int, int>
#define pll pair<long long, long long>
#define ll long long
#define ld long double
#define st first
#define nd second
#define pb push_back
#define INF INT_MAX
using namespace std;
const int N = 1e6 + 2;
pii nxt[N];
int deg[N];
bool mark[N];
ll diam[N], dist[N];
queue<int> q;
ll dp[N], qs[N];
void solve() {
int n; cin >> n;
for (int i = 1; i <= n; ++i) {
int b, w; cin >> b >> w;
nxt[i] = {b, w};
deg[b]++;
}
for (int i = 1; i <= n; ++i) if (deg[i] == 0) q.push(i);
while (!q.empty()) {
int cur = q.front(); q.pop();
auto [prt, w] = nxt[cur];
diam[prt] = max(diam[prt], max(diam[cur], dist[cur]+dist[prt]+w));
dist[prt] = max(dist[prt], dist[cur]+w);
deg[prt]--;
if (deg[prt] == 0) q.push(prt);
}
ll ans = 0;
for (int i = 1; i <= n; ++i) {
vector<pll> v;
ll cur = 0;
if (deg[i] != 0 && !mark[i]) {
int curr = i;
do {
mark[curr] = 1;
cur = max(cur, diam[curr]);
v.pb({dist[curr], nxt[curr].nd});
curr = nxt[curr].st;
} while (curr != i);
}
else continue;
int m = v.size();
for (int j = 0; j <= m+1; ++j) qs[j] = 0, dp[j] = 0;
for (int j = 1; j <= m; ++j) {
qs[j] = qs[j-1] + v[j-1].nd;
dp[j] = qs[j-1] + v[j-1].st;
}
for (int j = m-1; j > 0; --j) dp[j] = max(dp[j], dp[j+1]);
for (int j = 1; j < m; ++j) {
cur = max(cur, v[j-1].st - qs[j-1] + dp[j+1]);
}
for (int j = 0; j <= m+1; ++j) dp[j] = 0;
for (int j = m; j >= 1; --j) {
dp[j] = qs[j-1] + v[j-1].st;
}
for (int j = 2; j <= m; ++j) dp[j] = max(dp[j], dp[j-1]);
for (int j = 2; j <= m; ++j) {
cur = max(cur, qs[m] + v[j-1].st - qs[j-1] + dp[j-1]);
}
ans += cur;
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(NULL);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
}
Compilation message (stderr)
islands.cpp: In function 'void solve()':
islands.cpp:32:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
32 | auto [prt, w] = nxt[cur];
| ^
# | 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... |