wa30pts求助 码风良好,求大佬调,麻了已经
查看原帖
wa30pts求助 码风良好,求大佬调,麻了已经
760859
Let_Fly楼主2023/8/22 20:21
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e6+5;

int n,u;
int wei[N];
struct Edge{
    int p1,p2;
}eg[N];
vector<int> to[N];
int f[N];
int dp[N][2];
int ans;

void dfs(int nw,int fa,int y){
    dp[nw][1]=wei[nw],dp[nw][0]=0;
    if (nw == y) return;
	for(int v:to[nw]){
		if(v==fa)continue;
		dfs(v,nw,y);
		dp[nw][0]+=max(dp[v][0],dp[v][1]);
		dp[nw][1]+=dp[v][0];
	}

}

int find(int x){
    if(f[x]!=x)f[x]=find(f[x]);
    return f[x];
}

signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        f[i]=i;
        cin>>wei[i]>>u;
        to[u].push_back(i);
        to[i].push_back(u);
        eg[i]={u,i};
    }
    for(int i=1;i<=n;i++){
        int x=eg[i].p1,y=eg[i].p2;
        int k=find(x),l=find(y);
        if(k!=l) f[k]=l;
        else{
            dfs(x,y,y);
            int ansx=dp[x][0];
            // cout<<ansx<<'\n';
            dfs(y,x,x);
            int ansy=dp[y][0];
            // cout<<ansy<<'\n';
            ans+=max(ansx,ansy);
            // cout<<"ans"<<ans;
        }
    }
    cout<<ans;
    return 0;
}
2023/8/22 20:21
加载中...