题目描述
分析:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define MAXN 1000000
typedef long long LL;
struct node{
int v;
node *next;
}edge[MAXN*2+10],*adj[MAXN+10],*ecnt=&edge[0];
int n,fight[MAXN+10],r1,r2,flag,father[MAXN+10];
bool vis[MAXN+10];
LL ans,dp[MAXN+10][2];
void addedge(int u,int v)
{
node *p=++ecnt;
p->v=v;
p->next=adj[u];
adj[u]=p;
}
void read()
{
int x;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&fight[i],&x);
addedge(i,x);
addedge(x,i);
}
}
void dfs1(int u,int fa)
{
vis[u]=true,father[u]=fa;
for(node *p=adj[u];p;p=p->next){
if(p->v==fa) continue;
if(vis[p->v]&&father[p->v]!=u){
r1=u;
r2=p->v;
continue;
}
dfs1(p->v,u);
}
}
void dfs2(int u,int fa)
{
dp[u][0]=dp[u][1]=0;
father[u]=fa;
for(node *p=adj[u];p;p=p->next){
if(p->v==fa||p->v==flag||father[p->v]==u) continue;
dfs2(p->v,u);
dp[u][0]+=max(dp[p->v][0],dp[p->v][1]);
dp[u][1]+=dp[p->v][0];
}
dp[u][1]+=fight[u];
}
void DP()
{
memset(vis,0,sizeof vis);
for(int i=1;i<=n;i++){
if(vis[i]) continue;
r1=r2=-1;
memset(father,-1,sizeof father);
dfs1(i,0);
if(r1==-1){
flag=-1;
memset(father,-1,sizeof father);
dfs2(i,0);
ans+=max(dp[i][0],dp[i][1]);
}
else{
flag=r1;
dp[r1][0]=0;
memset(father,-1,sizeof father);
for(node *p=adj[r1];p;p=p->next){
if(p->v==r2) continue;
dfs2(p->v,r1);
dp[r1][0]+=max(dp[p->v][0],dp[p->v][1]);
}
LL tmp=dp[r1][0];
flag=r2;
dp[r2][0]=0;
memset(father,-1,sizeof father);
for(node *p=adj[r2];p;p=p->next){
if(p->v==r1) continue;
dfs2(p->v,r2);
dp[r2][0]+=max(dp[p->v][0],dp[p->v][1]);
}
ans+=max(tmp,dp[r2][0]);
}
}
}
int main()
{
read();
DP();
printf("%lld\n",ans);
}