QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#730064 | #9570. Binary Tree | ucup-team4074# | RE | 0ms | 0kb | C++17 | 2.3kb | 2024-11-09 18:31:12 | 2024-11-09 18:31:12 |
answer
#include<bits/stdc++.h>
#define int long long
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
using namespace std;
void solve();
signed main() {
// fast
int t = 1;
cin >> t;
while (t--) solve();
}
const int N = 2e5 + 10;
const int maxn=200010;
vector<int>e[maxn];
bool v[maxn];
int rt=0,rtmx=2e18,s[maxn],sum;
int n;
void getroot(int x,int fa)
{
if(fa==0)
{
rt=0;
rtmx=2e18;
}
s[x]=1;
int mx=0;
for(int i=0;i<e[x].size();i++)
{
int y=e[x][i];
if(y==fa||v[y]==0)continue;
getroot(y,x);
s[x]+=s[y];
mx=max(mx,s[y]);
}
mx=max(mx,sum-s[x]);
if(mx<rtmx)
{
rt=x;
rtmx=mx;
}
}
int ask(int x,int y)
{
cout<<"? "<<x<<" "<<y<<"\n";
cout.flush();
int r;
cin>>r;
return r;
}
void solve() {
cin>>n;
sum=n;
for(int i=1;i<=n;i++)
{
e[i].clear();
v[i]=1;
s[i]=0;
}
for(int i=1;i<=n;i++)
{
int u,v;
cin>>u>>v;
if(u)
{
e[i].push_back(u);
e[u].push_back(i);
}
if(v)
{
e[v].push_back(i);
e[i].push_back(v);
}
}
getroot(1,0);;
while(1)
{
int x=0,y=0;
for(int i=0;i<e[rt].size();i++)
{
if(!v[e[rt][i]])continue;
if(!x)x=e[rt][i];
else if(!y)y=e[rt][i];
}
if(!x&&!y)
{
cout<<"! "<<rt<<"\n";
return;
}
else if(!y)
{
if(ask(rt,x)==0)
{
cout<<"! "<<rt<<"\n";
cout.flush();
return;
}
else
{
cout<<"! "<<x<<"\n";
cout.flush();
return;
}
}
int vi=ask(x,y);
if(vi==0)
{
v[rt]=0;
sum=s[x];
getroot(x,0);
}
else if(vi==1)
{
sum=sum-s[y]-s[x];
v[x]=0;
v[y]=0;
getroot(rt,0);
}
else
{
v[rt]=0;
sum=s[y];
getroot(y,0);
}
}
}
详细
Test #1:
score: 0
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 2
output:
? 1 5 ? 4 3 ! 3