QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#749398 | #9570. Binary Tree | rdcamelot | RE | 0ms | 0kb | C++20 | 3.9kb | 2024-11-15 00:19:26 | 2024-11-15 00:19:26 |
answer
#include<bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
#define ll long long
const int inf=1e9;
const ll inff=1e18;
using i128=__int128;
void solve(){
int n;
cin>>n;
vector<vector<int>> adj(n+1);
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
if(x){
adj[i+1].emplace_back(x);
adj[x].emplace_back(i+1);
}
if(y){
adj[i+1].emplace_back(y);
adj[y].emplace_back(i+1);
}
}
vector<int> siz(n+1);
vector<int> w(n+1);
int sum=n;
int ct=-1; //centroid
auto dfs=[&](auto self,int u,int p)->void{
siz[u]=1;
for(int v:adj[u]){
if(v==p) continue;
self(self,v,u);
siz[u]+=siz[v];
}
};
auto get=[&](auto self,int u,int p)->void{
siz[u]=1;
w[u]=0;
for(int v:adj[u]){
if(v==p) continue;
self(self,v,u);
siz[u]+=siz[v];
w[u]=max(w[u],siz[v]);
}
w[u]=max(w[u],sum-siz[u]);
if(w[u]<=sum/2){
ct=u;
}
};
get(get,1,0);
vector<int> vis(n+1);
auto ask=[&](auto self,int u)->void{
dfs(dfs,u,0);
if(siz[u]==1){
cout<<"! "<<u<<'\n';
cout.flush();
return;
}
int v1=0,v2=0,v3=0;
for(int v:adj[u]){
if(vis[v]){
continue;
}
if(!v1){
v1=v;
}else if(!v2){
v2=v;
}else{
v3=v;
}
}
if(v3){
if(siz[v1]==min({siz[v1],siz[v2],siz[v3]})){
swap(v1,v3);
}
if(siz[v2]==min({siz[v1],siz[v2],siz[v3]})){
swap(v2,v3);
}
cout<<"? "<<v1<<' '<<v2<<'\n';
cout.flush();
int x;
cin>>x;
if(x==0){
int v=v1;
vis[u]=1;
sum=siz[v];
get(get,v,u);
self(self,ct);
return;
}
if(x==1){
vis[v1]=vis[v2]=1;
int v=u;
sum=siz[v3]+1;
get(get,v,u);
self(self,ct);
return;
}
if(x==2){
int v=v2;
vis[u]=1;
sum=siz[v];
get(get,v,u);
self(self,ct);
return;
}
}
if(v2){
cout<<"? "<<v1<<' '<<v2<<'\n';
cout.flush();
int x;
cin>>x;
if(x==0){
int v=v1;
vis[u]=1;
sum=siz[v];
get(get,v,u);
self(self,ct);
return;
}
if(x==1){
cout<<"! "<<u<<'\n';
cout.flush();
return;
}
if(x==2){
int v=v2;
vis[u]=1;
sum=siz[v];
get(get,v,u);
self(self,ct);
return;
}
}
if(v1){
cout<<"? "<<v1<<' '<<u<<'\n';
cout.flush();
int x;
cin>>x;
if(x==0){
cout<<"! "<<v1<<'\n';
cout.flush();
return;
}
if(x==2){
cout<<"! "<<u<<'\n';
cout.flush();
return;
}
}
};
ask(ask,ct);
}
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int t=1;
cin>>t;
while(t--){
solve();
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0
output:
? 3 1 ? 2 4 ? 5 2