P5018-对称二叉树
1 #include <bits/stdc++.h> 2 #define _for(i,a,b) for(int i = (a);i < b;i ++) 3 typedef long long ll; 4 using namespace std; 5 int N; 6 int vallist[1000003]; 7 int stlist[2][1000003]; 8 int rnt = 1; 9 inline ll read() 10 { 11 ll ans = 0; 12 char ch = getchar(), last = ' '; 13 while(!isdigit(ch)) last = ch, ch = getchar(); 14 while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); 15 if(last == '-') ans = -ans; 16 return ans; 17 } 18 inline void write(ll x) 19 { 20 if(x < 0) x = -x, putchar('-'); 21 if(x >= 10) write(x / 10); 22 putchar(x % 10 + '0'); 23 } 24 struct TreeNode 25 { 26 int val; 27 TreeNode *left; 28 TreeNode *right; 29 }; 30 TreeNode* build(int cur) 31 { 32 TreeNode* t = (TreeNode*)malloc(sizeof(TreeNode)); 33 t->val = vallist[cur]; 34 if(stlist[0][cur]==-1) 35 t->left = NULL; 36 else 37 t->left = build(stlist[0][cur]-1); 38 if(stlist[1][cur]==-1) 39 t->right = NULL; 40 else 41 t->right = build(stlist[1][cur]-1); 42 return t; 43 } 44 bool same(TreeNode* root1,TreeNode* root2) 45 { 46 if(!root1&&!root2) 47 return true; 48 if(!root1||!root2) 49 return false; 50 if(root1->val!=root2->val) 51 return false; 52 return same(root1->left,root2->right) && same(root1->right,root2->left); 53 } 54 int count(TreeNode* root) 55 { 56 if(!root) 57 return 0; 58 int k1 = count(root->left); 59 int k2 = count(root->right); 60 return k1+k2+1; 61 } 62 void f(TreeNode* root) 63 { 64 if(!root) 65 return ; 66 f(root->left); 67 f(root->right); 68 if(same(root,root)) 69 rnt = max(rnt,count(root)); 70 } 71 int main() 72 { 73 TreeNode* root; 74 N = read(); 75 _for(i,0,N) 76 vallist[i] = read(); 77 _for(i,0,N) 78 _for(j,0,2) 79 stlist[j][i] = read(); 80 root = build(0); 81 f(root); 82 write(rnt); 83 return 0; 84 }