1 /**************************************************************
2 Problem: 1040
3 User: Tunix
4 Language: C++
5 Result: Accepted
6 Time:2152 ms
7 Memory:64836 kb
8 ****************************************************************/
9
10 //BZOJ 1040
11 #include<vector>
12 #include<cstdio>
13 #include<cstring>
14 #include<cstdlib>
15 #include<iostream>
16 #include<algorithm>
17 #define rep(i,n) for(int i=0;i<n;++i)
18 #define F(i,j,n) for(int i=j;i<=n;++i)
19 #define D(i,j,n) for(int i=j;i>=n;--i)
20 #define pb push_back
21 using namespace std;
22 inline int getint(){
23 int v=0,sign=1; char ch=getchar();
24 while(ch<‘0‘||ch>‘9‘){ if (ch==‘-‘) sign=-1; ch=getchar();}
25 while(ch>=‘0‘&&ch<=‘9‘){ v=v*10+ch-‘0‘; ch=getchar();}
26 return v*sign;
27 }
28 const int N=1e6+10,INF=~0u>>2;
29 typedef long long LL;
30 /******************tamplate*********************/
31 int to[N<<1],next[N<<1],head[N],cnt;
32 void add(int x,int y){
33 to[++cnt]=y; next[cnt]=head[x]; head[x]=cnt;
34 to[++cnt]=x; next[cnt]=head[y]; head[y]=cnt;
35 }
36 /********************edge***********************/
37 int n,a[N],circle[N],tot;
38 LL f[N][2],ans,v[N];
39 int dfn[N],low[N],fa[N],dfs_clock;
40 bool vis[N];
41 void dfs(int x){
42 dfn[x]=low[x]=++dfs_clock;
43 for(int i=head[x];i;i=next[i])
44 if (to[i]!=fa[x]){
45 if (!dfn[to[i]]){
46 fa[to[i]]=x;
47 dfs(to[i]);
48 low[x]=min(low[x],low[to[i]]);
49 }else low[x]=min(low[x],dfn[to[i]]);
50 }
51 if (low[x]<dfn[x]) circle[++tot]=x;
52 }
53 void Tree_DP(int x){
54 vis[x]=1; f[x][1]=v[x]; f[x][0]=0;
55 for(int i=head[x];i;i=next[i])
56 if (!vis[to[i]]){
57 Tree_DP(to[i]);
58 f[x][1]+=f[to[i]][0];
59 f[x][0]+=max(f[to[i]][0],f[to[i]][1]);
60 }
61 }
62 int main(){
63 #ifndef ONLINE_JUDGE
64 freopen("1040.in","r",stdin);
65 freopen("1040.out","w",stdout);
66 #endif
67 n=getint();
68 F(i,1,n){
69 v[i]=getint();
70 a[i]=getint(); add(i,a[i]);
71 }
72 F(i,1,n) if (!dfn[i]){
73 dfs(i); LL tmp;
74 // F(i,1,tot) printf("%d ",circle[i]);puts("");
75 if (tot){
76 memset(vis,0,sizeof vis);
77 Tree_DP(circle[1]);
78 tmp=f[circle[1]][0];
79 memset(vis,0,sizeof vis);
80 Tree_DP(circle[2]);
81 tmp=max(tmp,f[circle[2]][0]);
82 }else{
83 Tree_DP(i);
84 tmp=max(f[i][0],f[i][1]);
85 }
86 ans+=tmp; tot=0;
87 }
88 printf("%lld\n",ans);
89 return 0;
90 }