求助几环树20分
查看原帖
求助几环树20分
235901
Always_Remember_It楼主2024/7/24 12:42
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e6+10;
int n,a[N],b[N],x,y,head[N],tot;
int dp[N][2];
bool vis[N];
struct Edge{
	int next,to;
}e[N];
void adde(int u,int v){
	e[++tot].next=head[u];
	e[tot].to=v;
	head[u]=tot;
	return;
}
bool dfs1(int u,int s){
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;
		if(v==s){
			x=u,y=v;
			return 1;
		}
		if(vis[v]) continue;
		vis[v]=1;
		if(dfs1(v,s)) return 1;
	}
	return 0;
}
void dfs2(int u,int y){
	if(u!=y) dp[u][1]+=a[u];
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;
		dfs2(v,y);
		dp[u][0]+=max(dp[v][0],dp[v][1]);
		if(u!=y) dp[u][1]+=dp[v][0];
	}
	return;
}
signed main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i]>>b[i];
		adde(b[i],i);
	}
	for(int i=1;i<=n;i++){
		if(!vis[i]){
			if(dfs1(i,i)) break;
		}
	}
	tot=0;
	memset(head,0,sizeof(head));
	memset(e,0,sizeof(e));
	for(int i=1;i<=n;i++){
		if(b[i]!=x||i!=y) adde(b[i],i);
	}
	dfs2(y,y);
	int maxn=dp[y][0];
	memset(dp,0,sizeof(dp));
	dfs2(y,x);
	maxn=max(maxn,max(dp[y][1],dp[y][0]));
	cout<<maxn<<endl;
	return 0; 
}
思路就是断环,不选x,不选y,取最大,但不知道哪里错了
2024/7/24 12:42
加载中...