1 #include<cstdio>
2 #include<cstdlib>
3 #include<cmath>
4 #include<cstring>
5 #include<algorithm>
6 #include<iostream>
7 #include<vector>
8 #include<map>
9 #include<set>
10 #include<queue>
11 #include<string>
12 #define inf 1000000000
13 #define maxn 1000000+1000
14 #define maxm 500+100
15 #define eps 1e-10
16 #define ll long long
17 #define pa pair<int,int>
18 #define for0(i,n) for(int i=0;i<=(n);i++)
19 #define for1(i,n) for(int i=1;i<=(n);i++)
20 #define for2(i,x,y) for(int i=(x);i<=(y);i++)
21 #define for3(i,x,y) for(int i=(x);i>=(y);i--)
22 #define mod 1000000007
23 using namespace std;
24 inline int read()
25 {
26 int x=0,f=1;char ch=getchar();
27 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
28 while(ch>=‘0‘&&ch<=‘9‘){x=10*x+ch-‘0‘;ch=getchar();}
29 return x*f;
30 }
31 int n,rt,ban,a[maxn],fa[maxn],head[maxn];
32 ll ans,f[maxn],g[maxn],w[maxn];
33 bool v[maxn];
34 struct edge{int go,next;}e[maxn];
35 inline void dfs(int x)
36 {
37 v[x]=1;
38 if(v[a[x]])rt=x;else dfs(a[x]);
39 }
40 inline void dp(int x)
41 {
42 f[x]=w[x];g[x]=0;v[x]=1;
43 if(x==ban)f[x]=-inf;
44 for(int i=head[x];i;i=e[i].next)
45 if(i!=rt&&e[i].go!=fa[x])
46 {
47 int y=e[i].go;
48 fa[y]=x;
49 dp(y);
50 f[x]+=g[y];
51 g[x]+=max(f[y],g[y]);
52 }
53 }
54 int main()
55 {
56 freopen("input.txt","r",stdin);
57 freopen("output.txt","w",stdout);
58 n=read();int x;
59 for1(i,n)e[i].go=i,w[i]=read(),a[i]=x=read(),e[i].next=head[x],head[x]=i;
60 for1(i,n)
61 if(!v[i])
62 {
63 dfs(i);
64 ban=a[rt];
65 dp(rt);
66 ll tmp=f[rt];
67 ban=0;
68 dp(rt);
69 tmp=max(tmp,g[rt]);
70 ans+=tmp;
71 }
72 printf("%lld\n",ans);
73 return 0;
74 }