#pragma GCC optimize ("Ofast")
#pragma GCC target ("avx2")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MOD = 1e9+7;
const int MX = 1e6+10;
const ll INF = 0x3f3f3f3f3f3f3f3f;
#define int long long
int n, m, a[MX], w[MX];
vector<int> adj[MX];
ll ans, ret;
vector<ll> V, S;
bool vv[MX];
inline int cycle(int u) {
if(vv[u]) return u;
vv[u] = 1;
int r = cycle(a[u]);
if(r) {
V.push_back(u);
S.push_back(w[u]);
if(r==u) return 0;
else return r;
}
vv[u] = 0;
return 0;
}
inline ll dfs(int u) {
ll mx = 0;
vv[u] = 1;
for(int v : adj[u]) {
if(!vv[v]) {
ll r = dfs(v) + w[v];
ret = max(ret, mx+r);
mx = max(mx, r);
}
}
return mx;
}
void solve(int u) {
V.clear(); S.clear();
cycle(u);
reverse(V.begin(), V.end());
reverse(S.begin(), S.end());
for(auto &v : V) v = dfs(v);
m = V.size();
for(int i = m-1; i > 0; --i) swap(S[i], S[i-1]);
for(int i = 1; i < m; ++i) S[i] += S[i-1];
ll m1 = -INF, m2 = -INF;
for(int i = 0; i < m; ++i) {
ret = max(ret, max(m1+S[i]+V[i], m2-S[i]+V[i]+S[m-1]));
m1 = max(m1, V[i]-S[i]);
m2 = max(m2, V[i]+S[i]);
}
}
#undef int
int main() {
cin.tie(0)->sync_with_stdio(0);
freopen("input.in", "r", stdin);
cin >> n;
for(ll div_t i = 1; i <= n; ++i) {
cin >> a[i] >> w[i];
adj[a[i]].push_back(i);
}
for(ll i = 1; i <= n; ++i)
if(!vv[i]) solve(i), ans+=ret, ret = 0;
cout << ans << "\n";
return 0;
}
Compilation message
islands.cpp: In function 'int main()':
islands.cpp:66:15: error: expected ';' before 'i'
66 | for(ll div_t i = 1; i <= n; ++i) {
| ^~
| ;
islands.cpp:66:16: error: 'i' was not declared in this scope
66 | for(ll div_t i = 1; i <= n; ++i) {
| ^
islands.cpp:66:29: error: expected ')' before ';' token
66 | for(ll div_t i = 1; i <= n; ++i) {
| ~ ^
| )
islands.cpp:66:3: warning: this 'for' clause does not guard... [-Wmisleading-indentation]
66 | for(ll div_t i = 1; i <= n; ++i) {
| ^~~
islands.cpp:66:31: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'for'
66 | for(ll div_t i = 1; i <= n; ++i) {
| ^~
islands.cpp:66:10: warning: unused variable 'div_t' [-Wunused-variable]
66 | for(ll div_t i = 1; i <= n; ++i) {
| ^~~~~
islands.cpp:66:33: error: 'i' was not declared in this scope
66 | for(ll div_t i = 1; i <= n; ++i) {
| ^
islands.cpp:64:10: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)', declared with attribute warn_unused_result [-Wunused-result]
64 | freopen("input.in", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~