# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
198900 | arnold518 | Islands (IOI08_islands) | C++14 | 2081 ms | 130532 KiB |
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;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 1e6;
int N;
vector<pii> adj[MAXN+1];
pii to[MAXN+1];
ll ans, val;
bool vis[MAXN+1];
vector<int> cyc;
ll A[MAXN+1], D[MAXN+1];
int AS, DS;
ll dfs(int now, ll dep)
{
vis[now]=true;
ll ret=dep;
ll ta=0, tb=0;
for(pii &nxt : adj[now])
{
if(vis[nxt.first]) continue;
ll p=dfs(nxt.first, dep+nxt.second);
ret=max(ret, p);
if(p>ta) tb=ta, ta=p;
else if(p>tb) tb=p;
}
val=max(val, ta+tb-dep-dep);
return ret;
}
int main()
{
int i, j;
scanf("%d", &N);
for(i=1; i<=N; i++)
{
int v, w;
scanf("%d%d", &v, &w);
to[i]={v, w};
adj[v].push_back({i, w});
}
for(i=1; i<=N; i++)
{
if(vis[i]) continue;
int now=i;
cyc=vector<int>(0);
while(!vis[now])
{
cyc.push_back(now);
vis[now]=1;
now=to[now].first;
}
reverse(cyc.begin(), cyc.end());
while(!cyc.empty() && cyc.back()!=now) vis[cyc.back()]=0, cyc.pop_back();
reverse(cyc.begin(), cyc.end());
AS=DS=0;
ll s=0; val=0;
D[DS++]=0;
for(i=0; i<cyc.size(); i++) A[AS++]=dfs(cyc[i], 0);
for(i=0; i<cyc.size(); i++) D[DS++]=(D[DS-1]+to[cyc[i]].second), s+=to[cyc[i]].second;
DS--;
ll t=-1e18;
for(j=0; j<cyc.size(); j++)
{
if(j) val=max(val, D[j]+A[j]+t);
t=max(t, A[j]-D[j]);
}
t=-1e18;
for(j=0; j<cyc.size(); j++)
{
if(j) val=max(val, s-D[j]+A[j]+t);
t=max(t, D[j]+A[j]);
}
ans+=val;
}
printf("%lld", ans);
}
Compilation message (stderr)
# | 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... |