QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#715096 | #9570. Binary Tree | OIer_kzc# | TL | 1ms | 3628kb | C++17 | 2.6kb | 2024-11-06 10:25:34 | 2024-11-06 10:25:35 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
#define dbg(x) cerr<<"In Line "<<__LINE__<<' '<<#x<<" = "<<(x)<<'\n'
bool no[100005],del[100005];
int cnt,ls[100005],rs[100005],siz[100005];
void dfs1(int u){
siz[u]=1;
if(ls[u]) dfs1(ls[u]),siz[u]+=siz[ls[u]];
if(rs[u]) dfs1(rs[u]),siz[u]+=siz[rs[u]];
}
void dele(int u,int skip){
del[u]=1,cnt--;
if(ls[u]&&ls[u]^skip) dele(ls[u],skip);
if(rs[u]&&rs[u]^skip) dele(rs[u],skip);
}
int main(){
int t;cin>>t;
while(t--){
int n;cin>>n,cnt=n;
for(int i=1;i<=n;i++) del[i]=0;
for(int i=1;i<=n;i++) cin>>ls[i]>>rs[i];
bool yes=0;
while(cnt>1){
for(int i=1;i<=n;i++) no[i]=0;
for(int i=1;i<=n;i++) if(!del[i]) no[ls[i]]=no[rs[i]]=1;
int rt,fa=0;
for(int i=1;i<=n;i++) if(!del[i]&&!no[i]) rt=i;
dfs1(rt);
int now=rt;
while(max(siz[ls[now]],siz[rs[now]])>siz[rt]>>1){
fa=now;
if(siz[ls[now]]>siz[rt]>>1) now=ls[now];else now=rs[now];
}
if(cnt==2){
cout<<"? "<<now<<' '<<(ls[now]|rs[now])<<endl;
int t;cin>>t;
if(!t) cout<<"! "<<now<<endl;
else cout<<"! "<<(ls[now]|rs[now])<<endl;
yes=1;break;
}
else if(!fa){
cout<<"? "<<ls[now]<<' '<<rs[now]<<endl;
int t;cin>>t;
if(!t) dele(now,ls[now]),ls[now]=0;
else if(t==1){
cout<<"! "<<now<<endl,yes=1;break;
}
else if(t==2) dele(now,rs[now]),rs[now]=0;
}
else if(ls[now]){
cout<<"? "<<fa<<' '<<ls[now]<<endl;
int t;cin>>t;
if(!t){
dele(now,0);
if(ls[fa]==now) ls[fa]=0;else rs[fa]=0;
}
if(t==1){
dele(rt,now),dele(ls[now],0),ls[now]=0;
}
if(t==2) dele(rt,ls[now]);
}
else if(rs[now]){
cout<<"? "<<fa<<' '<<rs[now]<<endl;
int t;cin>>t;
if(!t){
dele(now,0);
if(rs[fa]==now) rs[fa]=0;else ls[fa]=0;
}
if(t==1){
yes=1,cout<<"! "<<now<<endl;break;
}
if(t==2) dele(rt,rs[now]);
}
}
if(!yes) for(int i=1;i<=n;i++) if(!del[i]) cout<<"! "<<i<<endl;
}
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 1ms
memory: 3628kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 1 ? 2 5 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Time Limit Exceeded
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 2 2 0 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 2 1 2 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 1 0 2 5 4 5 3 1 0 0 0 0 0 0 0 0 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 1 2 5 3 0 5 1 0 0 0 0 4 0 0 0 5 5 0 0 0 0 0 3 0 2 4 1 2 3 3 0 1 0 0 0 2 2 2 0 0 0 2 3 2 3 0 0 0 0 2 10 2 8 9 7 0 0 ...
output:
? 1 8 ? 5 4 ? 4 3 ! 4 ? 5 3 ? 3 1 ? 2 4 ! 4 ? 3 5 ? 8 4 ? 1 8 ! 8 ? 2 4 ? 2 3 ! 2 ? 7 5 ? 3 2 ! 2 ? 5 1 ? 5 4 ! 5 ? 1 2 ? 5 3 ! 3 ? 2 3 ! 3 ? 1 2 ! 2 ? 2 3 ! 3 ? 1 9 ? 2 6 ? 4 3 ! 4 ? 1 2 ! 1 ? 5 9 ? 2 1 ? 2 6 ! 2 ? 3 10 ? 8 6 ? 10 8 ! 8 ? 9 3 ? 9 1 ? 2 7 ! 7 ? 2 1 ! 1 ? 4 3 ? 7 1 ! 1 ? 4 9 ? 4 8 ? ...