题目:
题意:
给出一棵树,要求我们通过最少的交换子树的次数使得一棵树的最小深度和最大深度差不大于 1 1 1,且左子树的深度要大于右子树的
分析:
我们在树上跑一次
d
f
s
dfs
dfs,求出最大深度和最小深度
如果差大于
1
1
1显然无解
现在我们来考虑哪些情况是必然需要交换的,设
1
1
1表示所有子树的深度较大,
2
2
2表示所有子树的深度有大有小,
0
0
0表示所有子树的深度较小(比较的对象是另一颗子树)
1.
1.
1.左子树为
0
0
0而右子树为
1
1
1,为了满足题意必定需要一次交换
2.
2.
2.左子树为
2
2
2而右子树为
1
1
1,我们为了保证左子树深度要更大,也需要一次交换,而左子树为
2
2
2的情况下,我们在之后对其子树讨论时再求解
3.
3.
3.左子树为
0
0
0而右子树为
2
2
2,与上面同理,为保证右子树深度更小同样要一次交换
这样就是所有情况了吗
n
o
,
n
o
,
n
o
no,no,no
no,no,no
我们还有两棵子树状态相同的情况没有讨论,当它们同时是
0
、
1
0、1
0、1时肯定不需要交换,当
2
2
2时呢,按照题意,我们必须要把深度大的往左移,小的往右移,可我们不能交换两个子树内的子树,所有这种情况是无解的
代码:
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<vector>
#define LL long long
using namespace std;
inline LL read() {
LL d=0,f=1;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
return d*f;
}
int t[100005][3],mind=2147483647/3,maxd=0;
void dig(int k,int dep)
{
if(!k) {mind=min(mind,dep);maxd=max(maxd,dep);return;}
dig(t[k][1],dep+1);dig(t[k][2],dep+1);
return;
}
int ans=0,tf=0;
int get(int k,int dep)
{
if(!k) {if(dep==mind) return 0;else return 1;}
int a=get(t[k][1],dep+1),b=get(t[k][2],dep+1);
if((a==0&&b==1)||(a==2&&b==1)||(a==0&&b==2)) ans++;
if(a==2||b==2) {if(a==b) tf=1;return 2;}
if(a+b==1) return 2;
else if(a+b==2) return 1;
else return 0;
}
int main()
{
int n=read();
for(int i=1;i<=n;i++)
{
int a=read(),b=read();
a+=(a==-1?1:0);b+=(b==-1?1:0);
t[i][1]=a;t[i][2]=b;
}
dig(1,0);
if(maxd-mind>1) return !printf("-1");
if(maxd==mind) return !printf("0");
get(1,0);
if(tf) printf("-1");
else cout<<ans;
return 0;
}