求差错,50分
查看原帖
求差错,50分
101975
OranJun楼主2019/7/11 19:50
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int vis[1000005],n,tot,head[2000005],x1,x2,E;
ll ans,f[1000005][2],c[1000005];
struct node{int to,next;}e[2000005];
void add(int u,int v){e[++tot].to=v;e[tot].next=head[u];head[u]=tot;}
void read(){
    scanf("%d",&n);
    for(int i=1,y;i<=n;i++){
        scanf("%lld %d",&c[i],&y);
        add(i,y);
        add(y,i);
    }
}
void dfs(int u,int h){//找环删边
    vis[u]=1;
    for(int i=head[u];i;i=e[i].next)
    {
        int v=e[i].to;
        if(v==h)continue;
        if(vis[v]){
            x1=u,x2=v;
            E=i;
            continue;
        }
        dfs(v,u);
    }
}
void dp(int u,int fa){
     f[u][0]=0;
     f[u][1]=c[u];
     for(int i=head[u];i;i=e[i].next){
        int v=e[i].to;
        if(v==fa)continue;
        if((u==x1&&v==x2)||(u==x2&&v==x1))continue;//这里不知道对不对
        dp(v,u);
        f[u][1]+=f[v][0];
        f[u][0]+=max(f[v][1],f[v][0]);
     }
} 
int main(){
    read();
    for(int i=1;i<=n;i++){
      if(vis[i])continue;
      dfs(i,0);
      dp(x1,-1);
      ll tmp=f[x1][0];
      dp(x2,-1);
      tmp=max(tmp,f[x2][0]);
      ans+=tmp;

    }
    cout<<ans<<endl;
}
2019/7/11 19:50
加载中...