QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#736138 | #9570. Binary Tree | wxgmjfhy | RE | 1ms | 3588kb | C++20 | 2.6kb | 2024-11-12 01:15:03 | 2024-11-12 01:15:03 |
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 cnt=0;
for(auto t:g[u]){
if(f[t])continue;
cnt++;
}
if(cnt==0){
ans=u;
return;
}
if(cnt==1){
for(auto t:g[u]){
if(f[t])continue;
ans=(query(t,u)==0?t:u);
return;
}
}
int son1=-1,son2=-1;
for(auto t:g[u]){
if(f[t])continue;
if(son1==-1)son1=t;
else son2=t;
}
int x=query(son1,son2);
if(x==0){
f[u]=1;
sum=sz[son1],rt=0;
find(find,son1,-1);
self(self,rt);
}else if(x==2){
f[u]=1;
sum=sz[son2],rt=0;
find(find,son2,-1);
self(self,rt);
}else{
int son=-1;
for(auto t:g[u]){
if(f[t]||t==son1||t==son2)continue;
son=t;
}
if(son==-1){
ans=u;
return;
}
f[son1]=f[son2]=1;
sum=sz[son]+1,rt=0;
find(find,u,-1);
self(self,rt);
}
};
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: 3588kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 2 0 2 0 2 0 0 2
output:
? 1 3 ? 3 4 ! 3 ? 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 0 0 2 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 2 1 0 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 0 0 2 5 4 5 3 1 0 0 0 0 0 0 1 2 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 0 0 5 3 0 5 1 0 0 0 0 4 0 0 2 5 5 0 0 0 0 0 3 0 2 4 1 0 3 3 0 1 0 0 0 2 2 2 0 0 0 0 3 2 3 0 0 0 0 2 10 2 8 9 7 0 0 ...
output:
? 2 4 ? 2 7 ? 2 1 ! 1 ? 5 3 ? 1 3 ? 2 4 ! 2 ? 1 6 ? 1 7 ? 1 5 ! 5 ? 4 2 ? 1 5 ! 5 ? 5 7 ? 1 4 ! 1 ? 5 1 ? 5 4 ! 4 ? 1 4 ? 5 2 ! 5 ? 3 2 ! 2 ? 1 2 ! 1 ? 2 3 ! 3 ? 2 5 ? 1 9 ? 9 10 ! 10 ? 1 2 ! 1 ? 5 9 ? 4 5 ? 3 8 ! 3 ? 5 8 ? 7 5 ? 3 1 ! 3 ? 3 9 ? 1 9 ? 2 7 ! 2 ? 1 2 ! 2 ? 4 6 ? 2 5 ! 5 ? 4 5 ? 2 3 ? ...