QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#762143 | #9570. Binary Tree | nahida_qaq | RE | 0ms | 0kb | C++23 | 3.3kb | 2024-11-19 13:54:50 | 2024-11-19 13:54:50 |
answer
#include <bits/stdc++.h>
#define int long long
#define io ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define pb push_back
using namespace std;
const int N=1e6+5,mod1=1e9+7,mod2=998244353,inf=1e18;
typedef pair<int,int> pi;
void solve()
{
int n;
cin>>n;
vector<vector<int>>g(n+5);
for(int i=1;i<=n;i++)
{
int x,y;
cin>>x>>y;
if(x)
{
g[i].pb(x);
g[x].pb(i);
}
if(y)
{
g[i].pb(y);
g[y].pb(i);
}
}
vector<int>size(n+5),weight(n+5);
vector<int>st(n+5);
int centroid=1;
int num=n;
function<void(int,int)>dfs1=[&](int u,int fa)
{
size[u]=1;
for(auto v:g[u])if(!st[v]&&v!=fa)
{
dfs1(v,u);
size[u]+=size[v];
}
};
function<void(int,int)>dfs2=[&](int u,int fa)
{
weight[u]=0;
for(auto v:g[u])if(!st[v]&&v!=fa)
{
dfs1(v,u);
weight[u]=max(weight[u],size[v]);
}
weight[u]=max(weight[u],num-size[u]);
if(weight[u]<=num/2)centroid=u;
};
while(num>1)
{
dfs1(centroid,0);
num=size[centroid];
dfs2(centroid,0);
int du=0;
for(auto i:g[centroid])if(!st[i])du++;
if(du==0)
{
cout<<'!'<<' '<<centroid<<endl;
return ;
}
if(du==1)
{
int x=0;
for(auto i:g[centroid])if(!st[i])
{
x=i;
break;
}
cout<<'?'<<' '<<centroid<<' '<<x<<endl;
int t;
cin>>t;
if(t==0)
{
cout<<'!'<<' '<<centroid<<endl;
return ;
}
st[centroid]=1;
centroid=x;
continue;
}
if(du==2)
{
int x=0,y=0;
for(auto i:g[centroid])if(!st[i])
{
if(!x)x=i;
else
{
y=i;
break;
}
}
cout<<'?'<<' '<<x<<' '<<y<<endl;
int t;
cin>>t;
if(t==1)
{
cout<<'!'<<' '<<centroid<<endl;
return ;
}
if(t==0)
{
st[centroid]=st[y]=1;
centroid=x;
continue;
}
st[centroid]=st[x]=1;
centroid=y;
continue;
}
int x=g[centroid][0],y=g[centroid][1],z=g[centroid][2];
int sx=size[x],sy=size[y],sz=size[z];
if(sx<sy)swap(x,y),swap(sx,sy);
if(sx<sz)swap(x,z),swap(sx,sz);
if(sy<sz)swap(y,z),swap(sy,sz);
cout<<'?'<<' '<<x<<' '<<y<<endl;
int t;
cin>>t;
if(t==0)
{
st[centroid]=st[z]=st[y]=1;
centroid=x;
continue;
}
if(t==1)
{
st[x]=st[y]=1;
continue;
}
st[centroid]=st[z]=st[x]=1;
centroid=y;
continue;
}
}
signed main()
{
io;
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 2 2
output:
? 1 2 ? 5 3 ? 3 4