赞
踩
原题链接:https://www.luogu.org/problemnew/show/P5018
给定二叉树,求其最大的对称子树。
与题解中流传的解法类似,主要是复杂度不好估计。
#include <iostream> #include <ctime> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <queue> #define forn(i, n) for (int i = 0; i < (int)(n); ++i) #define for1(i, n) for (int i = 1; i <= (int)(n); ++i) #define pb push_back using namespace std; typedef long long LL; const int N=1000000+5; struct Node{ int w; int l,r; }Tree[N]; bool issame(int x,int y){ if(x==-1&&y==-1) return 1; if(x==-1||y==-1) return 0; if(Tree[x].w!=Tree[y].w) return 0; if(!issame(Tree[x].l,Tree[y].r)) return 0; if(!issame(Tree[x].r,Tree[y].l)) return 0; return 1; } int d[N],ans=0,n; void dfs(int u){ int l=Tree[u].l,r=Tree[u].r; if(l==-1&&r==-1){ d[u]=1; return; } if(l!=-1) dfs(l); if(r!=-1) dfs(r); d[u]=(l!=-1?d[l]:0)+(r!=-1?d[r]:0)+1; // cout<<u<<" "<<d[u]<<endl; } void dfs_(int u){ int l=Tree[u].l,r=Tree[u].r; if(l==-1&&r==-1){ ans=max(ans,1); return; } if(issame(l,r)){ ans=max(ans,1+d[l]+d[r]); return ; } if(l!=-1) dfs_(l); if(r!=-1) dfs_(r); } int main() { #ifdef LOCAL_DEFINE freopen("P5018.in", "rt", stdin); #endif scanf("%d",&n); for1(i,n) scanf("%d",&Tree[i].w); for1(i,n) scanf("%d%d",&Tree[i].l,&Tree[i].r); dfs(1); dfs_(1); printf("%d\n",ans); #ifdef LOCAL_DEFINE cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; #endif return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。