QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#736048 | #9570. Binary Tree | wxgmjfhy | RE | 1ms | 3628kb | C++20 | 2.8kb | 2024-11-11 23:50:33 | 2024-11-11 23:50:33 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
int x;
inline int query(int a,int b){
cout<<"? "<<a<<" "<<b<<endl;
cin>>x;
return x;
}
int n;
inline void solve(){
cin>>n;
vector<vector<int> >g(n+1);
for(int i=1;i<=n;i++){
int a,b;
cin>>a>>b;
if(a)g[i].push_back(a),g[a].push_back(i);
if(b)g[i].push_back(b),g[b].push_back(i);
}
vector<int>mx(n+1),sz(n+1),f(n+1);
mx[0]=inf;
int sum=n,rt=0;
auto find=[&](auto self,int u,int fa)->void {
sz[u]=1,mx[u]=0;
for(auto t:g[u]){
if(t==fa||f[t])continue;
self(self,t,u);
sz[u]+=sz[t];
mx[u]=max(mx[u],sz[t]);
}
mx[u]=max(mx[u],sum-sz[u]);
if(mx[u]<mx[rt])rt=u;
};
find(find,1,-1);
auto dfs=[&](auto self,int u,int fa)->void {
sz[u]=1;
for(auto t:g[u]){
if(t==fa||f[t])continue;
self(self,t,u);
sz[u]+=sz[t];
}
};
int ans=-1;
auto wk=[&](auto self,int u)->void {
dfs(dfs,u,-1);
int son=-1,cnt=0;
for(auto t:g[u]){
if(f[t])continue;
cnt++;
if(son==-1||sz[t]>sz[son])son=t;
}
if(son==-1){
ans=u;
return;
}
int x=query(son,u);
if(x==0){
if(sz[son]==1){
ans=son;
return;
}
f[u]=1;
sum=sz[son],rt=0;
find(find,son,-1);
self(self,rt);
}else{
if(cnt==1){
ans=u;
return;
}else if(cnt==2){
f[son]=1;
sum=sz[g[u][g[u][1]==son]]+1,rt=0;
find(find,u,-1);
self(self,rt);
}else{
int ls=(g[u][0]==son?g[u][1]:g[u][0]);
int rs=(g[u][0]==ls?(g[u][1]==son?g[u][2]:g[u][1]):g[u][2]);
int x=query(ls,rs);
if(x==0){
f[u]=1;
sum=sz[ls],rt=0;
find(find,ls,-1);
self(self,rt);
}else if(x==2){
f[u]=1;
sum=sz[rs],rt=0;
find(find,rs,-1);
self(self,rt);
}else{
ans=u;
return;
}
}
}
};
wk(wk,rt);
cout<<"! "<<ans<<endl;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
// cout<<setiosflags(ios::fixed)<<setprecision(10);
int t=1;
cin>>t;
while(t--)solve();
return 0;
}
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 2 1 2 0 2 0 0 2
output:
? 3 2 ? 1 5 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Runtime Error
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 2 2 2 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 0 2 1 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 0 0 0 5 4 5 3 1 0 0 0 0 0 0 2 1 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 2 0 2 5 3 0 5 1 0 0 0 0 4 0 2 2
output:
? 2 8 ? 5 4 ? 4 3 ! 3 ? 3 7 ? 1 2 ? 4 3 ! 2 ? 1 8 ? 1 3 ? 1 5 ! 1 ? 2 1 ? 4 5 ! 1 ? 5 3 ? 6 7 ? 6 2 ! 2 ? 5 2 ? 3 1 ? 1 2