QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#751636 | #9570. Binary Tree | wht11# | TL | 1ms | 3684kb | C++20 | 2.8kb | 2024-11-15 19:56:34 | 2024-11-15 19:56:35 |
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>;
const int N = 2e5 + 5;
vector<int> G[N];
int siz[N], f[N], vis[N];
int lst = 0;
int mid = 0;
void dfs(int u, int fa)
{
f[u] = fa;
siz[u] = 1;
for (auto v : G[u])
{
if (v == fa || vis[v])
continue;
dfs(v, u);
siz[u] += siz[v];
}
if (siz[u] == lst / 2)
mid = u;
}
void delson(int u, int fa)
{
vis[u] = 1;
for (auto v : G[u])
{
if (v == fa || vis[v])
continue;
delson(v, u);
}
}
void delfa(int u, int fa, int x)
{
vis[u] = 1;
for (auto v : G[u])
{
if (v == fa || v == x || vis[v])
continue;
delfa(v, u, x);
}
}
void solve()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
G[i].clear();
vis[i] = 0;
f[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;
dfs(rt, 0);
if (lst == 3)
{
for (auto v : G[f[mid]])
{
if (vis[v] || v == mid)
continue;
cout << "? " << mid << " " << v << "\n";
cout.flush();
cin >> x;
if (x == 0)
{
cout << "! " << mid << "\n";
cout.flush();
}
else if (x == 1)
{
cout << "! " << f[mid] << "\n";
cout.flush();
}
else if (x == 2)
{
cout << "! " << v << "\n";
cout.flush();
}
return;
}
}
cout << "? " << f[mid] << " " << mid << "\n";
cout.flush();
cin >> x;
if (x == 0)
{
delson(mid, f[mid]); // 留父亲 删除儿子及其子树
rt = f[mid];
lst -= siz[mid];
}
else if (x == 2)
{
delfa(1, 0, mid); // 留儿子
rt = mid;
lst = siz[mid];
}
if (lst == 1)
{
cout << "! " << rt << "\n";
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: 3684kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 0 1 2 0 2 0 0 2
output:
? 2 3 ? 1 5 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Time Limit Exceeded
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 2 0 2 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 0 0 0
output:
? 2 8 ? 8 4 ? 8 5 ! 5 ? 3 7 ? 3 7 ? 3 7 ? 3 7