Submission #900408

#TimeUsernameProblemLanguageResultExecution timeMemory
900408abcvuitunggioIslands (IOI08_islands)C++17
90 / 100
894 ms131072 KiB
#include <bits/stdc++.h> using namespace std; const int mxn=1000001; const long long INF=1e18; vector <int> ke[mxn],V[mxn]; queue <int> q; int n,p[mxn],l[mxn],last[mxn],r[mxn],idx,x; bitset <mxn> ch; long long dp[mxn],dp2[mxn],d[mxn],val,res,a,b,sum,s; pair <long long, int> mx={-1,0},mx2={-1,0}; void dfs(int u){ for (int v:ke[u]){ d[v]=d[u]+l[v]; dfs(v); dp[u]=max(dp[u],dp[v]+l[v]); } } void dfs2(int u){ mx={-1,0},mx2={-1,0}; for (int v:ke[u]){ auto tmp=make_pair(dp[v]+l[v],v); if (tmp>mx){ mx2=mx; mx=tmp; } else mx2=max(mx2,tmp); } for (int v:ke[u]) dp2[v]=max(dp2[u],(mx.second==v?mx2.first:mx.first))+l[v]; for (int v:ke[u]) dfs2(v); } int f(int i){ return (r[i]==i?i:r[i]=f(r[i])); } int main(){ ios_base::sync_with_stdio(NULL);cin.tie(nullptr); cin >> n; for (int i=1;i<=n;i++){ cin >> p[i] >> l[i]; last[p[i]]++; } iota(r,r+n+1,0); for (int i=1;i<=n;i++) if (!last[i]) q.push(i); while (!q.empty()){ int u=q.front(); q.pop(); ch[u]=1; ke[p[u]].push_back(u); r[f(u)]=f(p[u]); if (!--last[p[u]]) q.push(p[u]); } for (int i=1;i<=n;i++) if (f(i)==i){ dfs(i); dfs2(i); } memset(last,0,sizeof(last)); for (int i=1;i<=n;i++){ vector <int>().swap(ke[i]); V[f(i)].push_back(i); } for (int i=1;i<=n;i++){ if (ch[i]) continue; sum=0,a=-INF,b=-INF; int j=i; while (true){ sum+=l[j]; ch[j]=1; last[p[j]]=j; j=p[j]; if (j==i) break; } val=0,s=sum; for (int j=last[i];;j=last[j]){ for (int u:V[j]) val=max(val,max(max(dp[u],dp2[u]),d[u]+max(a-s,b+sum+s))); a=max(a,dp[j]+s); b=max(b,dp[j]-s); s-=l[last[j]]; if (j==i) break; } res+=val; } cout << res; }
#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...