[Recursive] symmetrical binary tree

Original title Portal

Thinking


That point the way, this question is NOIP2019-pjT4, is known as the easiest ever T4, but ... I was this little konjac had four points (direct output 1), in retrospect, feel that time is really retarded ah, the most annoying is reading the title of this question can be found easily result was 3, even if it will not, directly output 1 to 3 obviously good than the direct output - it turns out, direct output 3 high scores terrible --32 points! ! ! This is simply white to 32 points ah! ! ! Himself was really stupid, but this question really is not difficult ah, then if you can own AC This question, and now I have already participated in a provincial election of kinky ...... uncomfortable ah QAQ

However, another point of view, he is now feeling himself once how mentally retarded, it seems that is a manifestation of their own progress, but also made great progress! Ah, well, I hope I will continue to progress in the future, when one day, I feel that he is very mentally disabled, I was really grown up!

Do not pull up, look at the idea of it:
we can easily think of using recursive method:
1. enumerate the root node, determine whether it is about two children nodes exist and if there are equal points and equal rights, it has been about recursion. left and right child nodes of the two children nodes to repeat the above determination.
2. Analyzing Symmetry binary tree, it can be calculated as a root node in the two symmetrical fork and the number of nodes of the tree takes the optimal value.

The code ~

Code


#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<stack>
#include<map>
using namespace std;

typedef long long ll;
ll n,flag,v[1000000],l[1000000],r[1000000];

void dc(ll x,ll y)
{
    if(x==-1&&y==-1)return;
    if(x==-1||y==-1||v[x]!=v[y])
    {
        flag=0;
        return;
    }
    dc(l[x],r[y]);
    dc(r[x],l[y]);
    return;
}
ll jc(ll x)
{
    ll ans=1;
    if(l[x]!=-1)ans+=jc(l[x]);
    if(r[x]!=-1)ans+=jc(r[x]);
    return ans;
}
int main()
{
    cin>>n;
    for(ll i=1;i<=n;i++)
    {
        cin>>v[i];
    }
    for(ll i=1;i<=n;i++)
    {
        cin>>l[i]>>r[i];
    }
    ll ans=1;
    for(ll i=1;i<=n;i++)
    {
        if(l[i]!=-1&&r[i]!=-1&&v[l[i]]==v[r[i]])
        {
            flag=1;
            dc(l[i],r[i]);
            if(flag==1)
            {
                ans=max(ans,jc(i));
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/gongdakai/p/11604820.html