社区讨论
正解~(有大量注释)
P5018[NOIP 2018 普及组] 对称二叉树参与者 7已保存回复 10
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 10 条
- 当前快照
- 1 份
- 快照标识符
- @mi7d2cxa
- 此快照首次捕获于
- 2025/11/20 19:41 4 个月前
- 此快照最后确认于
- 2025/11/20 19:41 4 个月前
#include<bits/stdc++.h>
using namespace std;
int v[1000001],l[1000001],r[1000001],fa[1000001],q[1000001],tot;//hey, give me some place to build!
bool dfs(int u1,int u2)
{
if(v[u1]!=v[u2])//are you same at your value? no? bye bye!
return false;
if(l[u1]>0||r[u2]>0)//you have left kid or you have right kid? or all?
{
if(!(l[u1]>0&&r[u2]>0))//oh... you are no same at kid!
return false;
bool tmp=dfs(l[u1],r[u2]);//lets's check your kid.
if(!tmp)//emmmmmm... naughty kid! go away!
return false;
tot+=2;//your size are bigger now:)
}
if(r[u1]>0||l[u2]>0)//same...
{
if(!(r[u1]>0&&l[u2]>0))
return false;
bool tmp=dfs(r[u1],l[u2]);
if(!tmp)
return false;
tot+=2;
}
return true;//wonderful! AC!
}
bool check(int u)
{
tot=1;
if(l[u]==-1&&r[u]==-1)//you are the smallist!
return true;
else if(!(l[u]>0&&r[u]>0))//you are a bad guy...
return false;
tot=3;//great: you are a good one:)
return dfs(l[u],r[u]);//check you now!
}
inline int read()//quike read is batter than scanf
{
int x=0;
char c;
while((c=getchar())<'0'||c>'9')
if(c=='-')
{
while((c=getchar())>='0'&&c<='9');
return -1;//no kid:(
}
x=c-'0';
while((c=getchar())>='0'&&c<='9')
x=x*10+(c-'0');//build your kid:)
return x;
}
int main()
{
//freopen("tree.in","r",stdin);
//freopen("tree.out","w",stdout);
int n=read();
for(int i=1;i<=n;i++)
v[i]=read();//how much?
for(int i=1;i<=n;i++)
{
l[i]=read();//your left kid?
r[i]=read();//your right kid?
}
for(int i=1;i<=n;i++)
{
if(l[i]>0)
fa[l[i]]=i;//who's your father?
if(r[i]>0)
fa[r[i]]=i;//who's your father?
}
int R;
for(int i=1;i<=n;i++)
if(!fa[i])//who's the ROOT?
{
R=i;
break;
}
int f=1,e=1,ans=0;//ans must be the best!
q[1]=R;//just wait and see!
while(f<=e)
{
int u=q[f++];
if(check(u))//good job, are you batter?
ans=max(ans,tot);
else//no, next one please.
{
if(l[u]>0)
q[++e]=l[u];//your kid will go too
if(r[u]>0)
q[++e]=r[u];//your kid will go too
}
}
printf("%d\n",ans);
return 0;
}
回复
共 10 条回复,欢迎继续交流。
正在加载回复...