DFS 80分求调教
查看原帖
DFS 80分求调教
651908
8NewOC楼主2023/10/3 15:02
#include<bits/stdc++.h>
using namespace std;

inline int read(){
	int ret=0,f=0; char ch=getchar();
	while(!isdigit(ch)){if(ch=='-') f=1; ch=getchar();}
	while(isdigit(ch)) ret=(ret<<1)+(ret<<3)+(ch^48),ch=getchar();
	return f?-ret:ret;
}
int a[1000001],l[1000001],r[1000001];
long long ans;
void dfs(int x,int y){
	if(a[r[x]]==a[l[y]]&&a[l[x]]==a[r[y]]&&x!=-1&&y!=-1&&x!=0&&y!=0&&x!=y){
		ans+=2;
	}
	if(x==y&&x>0&&y>0){
		ans++;
		dfs(l[x],r[y]);
	}
	else if((r[x]==-1&&l[y]==-1&&l[x]==-1&&r[y]==-1)||(r[x]==0&&l[y]==0&&l[x]==0&&r[y]==0)){
		return ;
	}
	
	else if(((r[x]==-1||l[y]==-1)&&r[x]!=l[y])||((r[y]==-1||l[x]==-1)&&r[y]!=l[x])){
		ans=0;
		return ;
	}
	else{
		if(a[r[x]]==a[l[y]]&&a[l[x]]==a[r[y]]){
			dfs(r[x],l[y]);
			dfs(l[x],r[y]);
		}
		else{
			ans=0;
			return ;
		}
	}
}
int main(){
	int n;
	n=read();
	for(int i=1;i<=n;i++){
		a[i]=read();
	}
	for(int i=1;i<=n;i++){
		l[i]=read(),r[i]=read();
	}
	long long mx=-1;
	for(int i=1;i<=n;i++){
		ans=0;
		dfs(i,i);
		mx=max(ans,mx);
	}
	cout<<mx;
	return 0;
}
2023/10/3 15:02
加载中...