QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#762152 | #9570. Binary Tree | nahida_qaq | RE | 0ms | 3788kb | C++23 | 3.2kb | 2024-11-19 13:57:51 | 2024-11-19 13:58:01 |
Judging History
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)>dfs=[&](int u,int fa)
{
size[u]=1;
weight[u]=0;
for(auto v:g[u])if(!st[v]&&v!=fa)
{
dfs(v,u);
size[u]+=size[v];
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)
{
int last=centroid;
dfs(centroid,0);
num=size[last];
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: 100
Accepted
time: 0ms
memory: 3788kb
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 2 2 0 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 2 2 2
output:
? 1 8 ? 5 4 ? 4 3 ! 4 ? 2 7 ? 7 5 ? 5 8 ? 8 6