题意
详情请跟随–题目链接: https://ac.nowcoder.com/acm/contest/19859/R
一棵有点权的有根树如果满足以下条件,则被轩轩称为对称二叉树:
1. 二叉树;
2. 将这棵树所有节点的左右子树交换,新树和原树对应位置的结构相同且点权相等。
Input
第一行一个正整数 𝑛,表示给定的树的节点的数目,规定节点编号 1~n,其中节点1 是树根。
第二行 𝑛 个正整数,用一个空格分隔,第 𝑖 个正整数 𝑣𝑖 代表节点 𝑖 的权值。
接下来 𝑛 行,每行两个正整数 𝑙 , 𝑟 ,分别表示节点 𝑖 的左右孩子的编号。如果不存在左 / 右孩子,则以 −1 表示。两个数之间用一个空格隔开。
Output
输出文件共一行,包含一个整数,表示给定的树的最大对称二叉子树的节点数。
Example Input
10
2 2 5 5 5 5 4 4 2 3
9 10
-1 -1
-1 -1
-1 -1
-1 -1
-1 2
3 4
5 6
-1 -1
7 8
Example Output
3
#解析 :
解析&&细节,见以下注释
AC代码 - - -
#solution1
import java.util.*;
import java.io.*;
public class Main {
static int mxm = 1000005;
static int tree[][] = new int[mxm][2],a[] = new int[mxm], mx;
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int ini() throws IOException{
int x=0,c=in.read(),f=1;while(c<48||c>57){if(c=='-')f=-1;c=in.read();}
while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48);c=in.read();} return x*f;
}
static boolean dfs(int l, int r) {
if(l==-1&&r==-1) return true;
if(l==-1||r==-1) return false;
if(a[l]!=a[r]) return false;
mx+=2;
return dfs(tree[l][0],tree[r][1])&&dfs(tree[l][1],tree[r][0]);
}
public static void main(String[] args) throws IOException {
int n = ini(),t = 0, i = 0, ans = 1;
for(i = 1; i <= n; ++i) {
a[i] = ini();
}
for(i = 1; i <= n; ++i) {
tree[i][0] = ini();
tree[i][1] = ini();
}
for(i = 1; i <= n; ++i) {
mx = 1;
if(dfs(tree[i][0], tree[i][1])) {
ans = Math.max(ans,mx);
}
}
System.out.printf("%d\n", ans);
}
}