跳到正文

题解

题解 P5018 【对称二叉树】

水的第一步约 2 分钟
原文

这是 2025年10月24日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2018年11月13日
收录
2025年12月12日
更新
2026年10月24日
篇幅
约 2 分钟
题目
P5018

版本

  1. v2当前
  2. v1

暴力出奇迹

C++
#include<bits/stdc++.h>
#define ll long long
#define INF 2147483647
#define ll_INF 9223372036854775807
using namespace std;
inline int read(){
    int x = 0,tmp = 1;char ch = getchar();
    while( ch < '0' || ch > '9' ) {if ( ch == '-' ) tmp = -1; ch = getchar();}
    while( ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar(); }
    return x * tmp;
}
inline void write( int k ){
    if ( k < 0 ) { putchar( '-' ); k = -k;}
    if ( k > 9 ) write( k / 10 );
    putchar( k % 10 + '0' );
}
int n,ans;
int v[1000010],tre[1000010][2],num[1000010];

bool like(int a,int b){
	if(a==b) return 1;
	if(!a||!b) return 0;
	return v[a]==v[b]&&like(tre[a][0],tre[b][1])&&like(tre[a][1],tre[b][0]);
}

void dfs(int x){
	if(!x) return;
	dfs(tre[x][0]);
	dfs(tre[x][1]);
	num[x]=1+num[tre[x][0]]+num[tre[x][1]];
	v[x]=v[x]+v[tre[x][0]]+v[tre[x][1]];
	if(ans<num[x]&&like(tre[x][0],tre[x][1]))
	  ans=num[x];
}

int main(){
	n=read();
	for(int i=1;i<=n;i++) v[i]=read();
	v[0]=10010;
	for(int i=1;i<=n;i++)
	  for(int k=0;k<2;k++){
		tre[i][k]=read();
		if(tre[i][k]==-1) 
		   tre[i][k]=0;
	}
	dfs(1);
	write(ans);
	return 0;
}