【NOIP2018PJ正式赛】对称二叉树

暴力dfs即可。

#include<cstdio>
#define N 1000010
using namespace std;
int n,v[N],l[N],r[N],son[N],ans=0;

inline int read()
{
	int x=0,f=0; char c=getchar();
	while (c<'0' || c>'9') f=(c=='-') ? 1:f,c=getchar();
	while (c>='0' && c<='9') x=x*10+c-48,c=getchar();
	return f ? -x:x;
}

bool pd(int x,int y)
{
	if (x==-1 && y==-1) return 1;
	if (x==-1 || y==-1) return 0;
	if (v[x]!=v[y]) return 0;
	return pd(l[x],r[y])&pd(r[x],l[y]);
}

void dfs(int x)
{
	son[x]=1;
	if (l[x]!=-1) dfs(l[x]),son[x]+=son[l[x]];
	if (r[x]!=-1) dfs(r[x]),son[x]+=son[r[x]];
	if (son[x]>ans && pd(l[x],r[x])) ans=son[x];
}

int main()
{
	freopen("tree.in","r",stdin);
	freopen("tree.out","w",stdout);
	n=read();
	for (int i=1;i<=n;i++) v[i]=read();
	for (int i=1;i<=n;i++) l[i]=read(),r[i]=read();
	dfs(1);
	printf("%d
",ans);
	return 0;
}
转载需注明出处。
原文地址:https://www.cnblogs.com/jz929/p/11817738.html