QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#737248 | #9570. Binary Tree | oqmsac | ML | 0ms | 7728kb | C++23 | 3.0kb | 2024-11-12 15:12:21 | 2024-11-12 15:12:22 |
Judging History
answer
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define pii pair<ll,ll>
using namespace std;
#pragma GCC optimize(3)
#define N 1000005
ll cnt[N],fa[N];
vector<ll> e[N];
void dfs(ll p)
{
cnt[p]=1;
for(int i=0;i<e[p].size();i++)
{
dfs(e[p][i]);
cnt[p]+=cnt[e[p][i]];
}
if(e[p].size()>=2&&cnt[e[p][0]]<cnt[e[p][1]])
{
swap(e[p][0],e[p][1]);
}
}
void solve(ll root,ll n)
{
cerr<<n<<endl;
fa[root]=0;
if(n==1)
{
cout<<"! "<<root<<endl;
cout.flush();
return;
}
if(n==2)
{
cout<<"? "<<root<<' '<<e[root][0]<<endl;
cout.flush();
ll op;
cin>>op;
if(op==0)
{
cout<<"! "<<root<<endl;
cout.flush();
}
else
{
cout<<"! "<<e[root][0]<<endl;
cout.flush();
}
return;
}
ll p=root;
while(cnt[e[p][0]]>n/2) p=e[p][0];
if(e[p].size()<2||(fa[p]&&n-cnt[p]>cnt[e[p][1]]))
{
cout<<"? "<<fa[p]<<' '<<e[p][0]<<endl;
cout.flush();
ll op;
cin>>op;
if(op==0)
{
ll tt=cnt[p],pos=fa[p];
while(pos)
{
cnt[pos]-=tt;
pos=fa[pos];
}
if(e[fa[p]].size()>1)
{
e[fa[p]][0]=e[fa[p]][1];
}
e[fa[p]].pop_back();
solve(root,cnt[root]);
}
else if(op==1)
{
cnt[p]-=cnt[e[p][0]];
if(e[p].size()>1)
{
e[p][0]=e[p][1];
}
e[p].pop_back();
solve(p,cnt[p]);
}
else
{
solve(e[p][0],cnt[e[p][0]]);
}
}
else
{
cout<<"? "<<e[p][0]<<' '<<e[p][1]<<endl;
cout.flush();
ll op=0;
cin>>op;
if(op==0)
{
solve(e[p][0],cnt[e[p][0]]);
}
else if(op==1)
{
cout<<"! "<<p<<endl;
cout.flush();
return;
}
else
{
solve(e[p][1],cnt[e[p][1]]);
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
// freopen("")
int T;
cin>>T;
while(T--)
{
ll n;
cin>>n;
for(int i=0;i<=n;i++)
{
e[i].clear();
cnt[i]=0;
fa[i]=0;
}
for(int i=1;i<=n;i++)
{
ll x,y;
cin>>x>>y;
if(x) { e[i].push_back(x);fa[x]=i; }
if(y) { e[i].push_back(y);fa[y]=i; }
}
ll root=1;
for(int i=1;i<=n;i++)
{
if(!fa[i])
{
root=i;
dfs(i);
break;
}
}
solve(root,n);
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 0ms
memory: 7728kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 1 ? 2 5 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Memory Limit Exceeded
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
output:
? 8 6 ? 4 5 ? 4 3 ! 3 ? 5 3 ? 1 4 ! 2