ioi2008 island spoj 基环树dp
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define M 1000010
#define ll long long
int e[M],ne[M],been[M],v[M],t[M],nn,qu[M],bo,he;
ll w[M],dp[M],ans,tot,d[M*2];
int n;
int inc[M],a1[M*2],an;
void add(int x,int y){
ne[++nn]=e[x],v[nn]=y,e[x]=nn;
}
void solv(int x){
int i;
qu[he=bo=1]=x;
while(he>=bo)for(i=e[x=qu[bo++]];i;i=ne[i])if(!inc[v[i]])been[v[i]]=1,qu[++he]=v[i];
for(i=he;i>1;i--){
ans=max(ans,dp[t[qu[i]]]+dp[qu[i]]+w[qu[i]]);
dp[t[qu[i]]]=max(dp[t[qu[i]]],dp[qu[i]]+w[qu[i]]);
}
}
void findc(int x){
int i,j=x;
ans=0;
for(;!been[j];been[j]=1,j=t[j]);
x=t[j],an=1;
a1[1]=j;
inc[j]=1;
while(x!=j){
a1[++an]=x,inc[x]=1;
x=t[x];
}
for(i=1;i<=an;i++)solv(a1[i]),a1[i+an]=a1[i];
for(i=1;i<=(an<<1);i++)d[i]=d[i-1]+w[a1[i-1]];
qu[he=bo=1]=1;
for(i=2;i<=(an<<1);i++){
if(i-qu[bo]>=an)bo++;
ans=max(ans,dp[a1[i]]+dp[a1[qu[bo]]]+d[i]-d[qu[bo]]);
while(he>=bo&&dp[a1[i]]-d[i]>=dp[a1[qu[he]]]-d[qu[he]])he--;
qu[++he]=i;
}
tot+=ans;
}
int main(){
int i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)scanf("%d%lld",&t[i],&w[i]),add(t[i],i);
for(i=1;i<=n;i++)if(!been[i])findc(i);
cout<<tot;
}