QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#759077 | #9570. Binary Tree | wht11 | ML | 1ms | 3568kb | C++20 | 3.3kb | 2024-11-17 21:29:29 | 2024-11-17 21:29:30 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using PII = pair<int, int>;
#define endl "\n"
const int N = 1e5 + 5;
vector<int> G[N];
int siz[N],vis[N];
int lst = 0;
int mid = 0;
void dfs(int u, int fa)
{
siz[u] = 1;
int flag = 1;
for (auto v : G[u])
{
if (v == fa || vis[v])
continue;
dfs(v, u);
if (siz[v] > lst / 2)
flag = 0;
siz[u] += siz[v];
}
if (vis[u])
return;
if (lst - siz[u] > lst / 2)
flag = 0;
if (flag)
mid = u;
}
void solve()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
G[i].clear();
vis[i] = 0;
siz[i] = 0;
}
for (int i = 1; i <= n; i++)
{
int u, v;
cin >> u >> v;
if (v)
{
G[i].push_back(v);
G[v].push_back(i);
}
if (u)
{
G[i].push_back(u);
G[u].push_back(i);
}
}
lst = n;
int rt = 1;
mid = 0;
while (1)
{
int x;
mid = rt;
dfs(rt,0);
dfs(mid,0);
lst=siz[mid];
//cerr << "mid " << mid << endl;
vector<pair<int, int>> ve;
for (auto v : G[mid])
{
if (vis[v])
continue;
ve.emplace_back(siz[v], v);
}
sort(ve.begin(), ve.end());
int num=ve.size();
if (num == 3)
{
cout << "? " << ve[1].second << " " << ve[2].second << endl;
cout.flush();
cin >> x;
if (x == 0)
{
vis[mid]=1;
rt = ve[1].second;
}
else if (x == 1)
{
vis[ve[1].second] = 1;
vis[ve[2].second] = 1;
rt=mid;
}
else
{
vis[mid]=1;
rt = ve[2].second;
}
}
else if (num== 2)
{
cout << "? " << ve[0].second << " " << ve[1].second << endl;
cout.flush();
cin >> x;
if (x == 0)
{
vis[mid] = 1;
rt = ve[0].second;
}
else if (x == 1)
{
cout << "! " << mid << endl;
return;
}
else
{
vis[mid] = 1;
rt = ve[1].second;
}
}
else if (num == 1)
{
cout << "? " << mid << " " << ve[0].second << endl;
cout.flush();
cin >> x;
if (x == 0)
{
cout << "! " << mid << endl;
cout.flush();
}
else
{
cout << "! " << ve[0].second << endl;
cout.flush();
}
return;
}
else
{
cout << "! " << rt << endl;
cout.flush();
return;
}
}
}
signed main()
{
IOS;
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: 3568kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 2 0 2 0 2 0 0 2
output:
? 5 3 ? 3 4 ! 3 ? 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 2 2 2 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 2 2
output:
? 6 8 ? 5 4 ? 4 3 ! 3 ? 2 7 ? 7 5 ! 5