QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#716226 | #9570. Binary Tree | KJJD# | RE | 0ms | 0kb | C++20 | 2.6kb | 2024-11-06 14:42:12 | 2024-11-06 14:42:17 |
answer
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
vector<int> p[N];
int siz[N];
int root = 0;
int ma = 1e9;
int query(int u, int v)
{
cout << "? " << u << ' ' << v << endl;
int x;
cin >> x;
return x;
}
void answer(int x)
{
cout << "! " << x << endl;
return;
}
void dfs1(int u, int fa)
{
siz[u] = 1;
for (int v : p[u])
{
if (v == fa)
continue;
dfs1(v, u);
siz[u] += siz[v];
}
}
void dfs2(int u, int fa, int pre_s)
{
int tmp = pre_s;
int sum = pre_s;
for (int v : p[u])
{
if (v == fa)
continue;
sum += siz[v];
tmp = max(tmp, siz[v]);
}
if (tmp < ma)
{
ma = tmp;
root = u;
}
for (int v : p[u])
{
if (v == fa)
continue;
dfs2(v, u, sum - siz[v]);
}
}
void solve()
{
int n, m, k;
cin >> n;
for (int i = 1; i <= n; i++)
p[i].clear();
vector<int> du(n + 1, 0);
for (int i = 1; i <= n; i++)
{
int u, v;
cin >> u >> v;
du[u]++, du[v]++;
if (u)
p[i].push_back(u), p[u].push_back(i);
if (v)
p[i].push_back(v), p[v].push_back(i);
}
for (int i = 1; i <= n; i++)
if (!du[i])
root = i;
ma = n;
dfs1(root, 0);
dfs2(root, 0, 0);
int f1 = -1;
while (p[root].size() >= 1)
{
auto tmp = p[root];
if (tmp.size() < 2)
tmp.push_back(root);
f1 = query(tmp[0], tmp[1]);
if (f1 == 0)
{
p[tmp[0]].erase(find(p[tmp[0]].begin(), p[tmp[0]].end(), root));
root = tmp[0];
}
else if (f1 == 1)
{
p[root].clear();
if (tmp.size() >= 3 && tmp[2] != root)
p[root].push_back(tmp[2]);
}
else
{
if (tmp[1] != root)
{
p[tmp[1]].erase(find(p[tmp[1]].begin(), p[tmp[1]].end(), root));
root = tmp[1];
}
else
{
p[root].clear();
}
}
ma=n;
dfs1(root,0);
dfs2(root, 0, 0);
}
answer(root);
}
int main()
{
// #ifdef LOCAL
// freopen("data.in", "r", stdin);
// freopen("data.out", "w", stdout);
// #endif
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T;
cin >> T;
while (T--)
solve();
return 0;
}
详细
Test #1:
score: 0
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0
output:
? 1 5 ? 3 4 ? 3 2