QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#728333 | #9570. Binary Tree | Time_stop | TL | 0ms | 0kb | C++17 | 2.4kb | 2024-11-09 14:59:18 | 2024-11-09 14:59:20 |
answer
#include<bits/stdc++.h>
using namespace std;
const int M=1e5+5;
int n,fa[M],du[M];
int centroid[2];
int siz[M],weight[M];
int has[M];
struct node{
int l,r;
}tr[M];
void getCentroid(int u){
siz[u]=1;
weight[u]=0;
int l=tr[u].l,r=tr[u].r;
if(l!=0&&!has[l])
{
getCentroid(l);
siz[u]+=siz[l];
weight[u]=max(weight[u],siz[l]);
}
if(r!=0&&!has[r])
{
getCentroid(r);
siz[u]+=siz[r];
weight[u]=max(weight[u],siz[r]);
}
weight[u]=max(weight[u],n-siz[u]);
if(weight[u]<=n/2){
centroid[centroid[0] != 0] = u;
}
}
void solve(){
cin>>n;
for(int i=0;i<=n;i++){
tr[i].l=tr[i].r=fa[i]=du[i]=has[i]=0;
}
for(int i=1;i<=n;i++){
cin>>tr[i].l>>tr[i].r;
fa[tr[i].l]=fa[tr[i].r]=i;
du[tr[i].l]++; du[tr[i].r]++;
int tmp=2;
if(tr[i].l==0) tmp--;
if(tr[i].r==0) tmp--;
du[i]+=tmp;
}
int root;
for(int i=1;i<=n;i++){
if(!fa[i]){
root=i; break;
}
}
while(1){
getCentroid(root);
int cur=centroid[0];
if(du[cur]==0){
cout<<"! "<<cur<<endl;
cout.flush();
break;
}else if(du[cur]==1){
int u,v,tmp;
if(tr[cur].l!=0&&!has[tr[cur].l]) v=tr[cur].l;
else if(tr[cur].r!=0&&!has[tr[cur].r]) v=tr[cur].r;
else v=fa[cur];
cout<<"? "<<cur<<" "<<v<<endl; cout.flush();
cin>>tmp;
cout<<"! ";
if(tmp==1) cout<<cur<<endl;
else cout<<v<<endl;
cout.flush();
break;
}else if(du[cur]==2){
int u,v,tmp;
if(tr[cur].l!=0&&!has[tr[cur].l]){
u=tr[cur].l;
}
if(tr[cur].r!=0&&!has[tr[cur].r]){
if(!u) u=tr[cur].r;
else v=tr[cur].r;
}
if(fa[cur]!=0&&!has[fa[cur]]){
if(!u) u=fa[cur];
else v=fa[cur];
}
cout<<"? "<<u<<" "<<v<<endl; cout.flush();
cin>>tmp;
if(tmp==1) {
cout<<"! "<<cur<<endl;
cout.flush();
}
else if(tmp==0) {
root=u; n=siz[u]; du[u]--; continue;
}
else if(tmp==2){
if(v==tr[cur].r){
root=v; n=siz[v]; du[v]--; continue;
}else{
n-=siz[cur]; has[cur]++; du[fa[cur]]--; continue;
}
}
}
else if(du[cur]==3){
int u,v,w,tmp;
u=tr[cur].l,v=tr[cur].r,w=fa[cur];
cout<<"? "<<u<<" "<<v; cout.flush();
cin>>tmp;
if(tmp==0){
root=u; n=siz[u]; du[u]--; continue;
}else if(tmp==1){
n-=siz[u];n-=siz[v]; has[u]++; has[v]++; du[cur]-=2; continue;
}else if(tmp==2){
root=v; n=siz[v]; du[v]--; continue;
}
}
}
}
int main(){
int t;cin>>t;
while(t--){
solve();
}
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Time Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0
output:
? 1 5