QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#715077 | #9570. Binary Tree | OIer_kzc# | TL | 1ms | 3720kb | C++17 | 2.6kb | 2024-11-06 10:18:33 | 2024-11-06 10:18:34 |
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];
int fa;
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;
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(cnt==3&&ls[now]&&rs[now]){
cout<<"? "<<ls[now]<<' '<<rs[now]<<endl;
int t;cin>>t;
if(!t) cout<<"! "<<ls[now]<<endl;
else if(t==1) cout<<"! "<<now<<endl;
else if(t==2) cout<<"! "<<rs[now]<<endl;
yes=1;break;
}
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;
}
}
詳細信息
Test #1:
score: 100
Accepted
time: 1ms
memory: 3720kb
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
output:
? 1 8 ? 1 5 ! 5