57pts求调
查看原帖
57pts求调
1215754
Cultural_Revolution楼主2024/12/26 21:26
#include<iostream>
#include<cstring>
using namespace std;

const int N=2e5+5;
int n,ne[2*N],e[2*N],h[2*N],idx=0,flag=0,ans=0;
void add(int x,int y)
{
    e[idx]=y;ne[idx]=h[x];h[x]=idx++;
}
int dfs(int x,int &maxx)//maxx为最大深度,dfs返回最小深度
{
   int maxxl=0,maxxr=0;
    if(x==-1)//-1直接返回
    {
        maxx=1;
        return 1;
    }
    int r=dfs(e[h[x]],maxxr);//递归右子树
    int l=dfs(e[ne[h[x]]],maxxl);//左子树
    maxx=max(maxxl,maxxr)+1;//最大深度
    if(r==-1||l==-1||abs(maxxl-r)>1||abs(maxxr-l)>1) return -1;//若左右子树深度相差大于一直接返回-1
    if(l==r||l-r==1) return r+1;//左子树最小深度
    else if(r-l==1)
    {
        ans++;
        return l+1;
    }
    else return -1;     
}
int main()
{
    memset(h,-1,sizeof h);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x,y;
        cin>>x>>y;
        add(i,x);//左
        add(i,y);//右
    }
    int a;
    if(dfs(1,a)==-1) cout<<-1;
    else cout<<ans;
}
2024/12/26 21:26
加载中...