QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#749075 | #9570. Binary Tree | SkyEyeController | TL | 0ms | 0kb | C++23 | 4.2kb | 2024-11-14 22:33:24 | 2024-11-14 22:33:24 |
answer
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
const i64 mod = 998244353;
vector<vector<int>> con;
vector<int> ctr; // 重心
const int maxn = 2e5 + 9;
int n, m, allsz;
int sz[maxn], mss[maxn], fa[maxn];
void dfs(int u, int f)
{
fa[u] = f;
sz[u] = 1, mss[u] = 0;
for (auto v : con[u])
{
if (v == f)
continue;
dfs(v, u);
sz[u] += sz[v];
mss[u] = max(mss[u], sz[v]);
}
mss[u] = max(mss[u], allsz - sz[u]);
if (mss[u] <= allsz / 2)
{
ctr.push_back(u);
}
} // 搜重心
void solve()
{
cin >> n;
con.assign(n + 1, vector<int>());
ctr.clear();
int rt = 1;
for (int i = 1; i <= n; i++)
{
int l, r;
cin >> l >> r;
if (l)
{
con[i].push_back(l);
con[l].push_back(i);
}
if (r)
{
con[i].push_back(r);
con[r].push_back(i);
}
}
for (int i = 1; i <= n; i++)
{
sort(con[i].begin(), con[i].end());
con[i].erase(unique(con[i].begin(), con[i].end()), con[i].end());
}
function<int(int, int)> ask = [&](int l, int r) -> int
{
cout << "? " << l << " " << r << endl;
cout.flush();
int x;
cin >> x;
return x;
};
allsz = n;
dfs(rt, 0);
rt = ctr[0];
ctr.clear();
dfs(rt, 0);
while (sz[rt] > 1)
{
if (con[rt].size() == 2)
{
int l = con[rt][0], r = con[rt][1];
int seg = ask(l, r);
if (seg == 0)
{
auto it = find(con[l].begin(), con[l].end(), rt);
if (it != con[l].end())
con[l].erase(it);
allsz = sz[l];
ctr.clear();
dfs(l, 0);
rt = ctr[0];
ctr.clear();
dfs(rt, 0);
}
else if (seg == 2)
{
auto it = find(con[r].begin(), con[r].end(), rt);
if (it != con[r].end())
con[r].erase(it);
allsz = sz[r];
ctr.clear();
dfs(r, 0);
rt = ctr[0];
ctr.clear();
dfs(rt, 0);
}
else
{
cout << "! " << rt << endl;
return;
}
}
else if (con[rt].size() > 2)
{
sort(con[rt].rbegin(), con[rt].rend(), [&](int x, int y) -> bool
{ return sz[x] < sz[y]; });
int l = con[rt][0], r = con[rt][1];
int seg = ask(l, r);
if (seg == 0)
{
auto it = find(con[l].begin(), con[l].end(), rt);
if (it != con[l].end())
con[l].erase(it);
allsz = sz[l];
ctr.clear();
dfs(l, 0);
rt = ctr[0];
ctr.clear();
dfs(rt, 0);
}
else if (seg == 2)
{
auto it = find(con[r].begin(), con[r].end(), rt);
if (it != con[r].end())
con[r].erase(it);
allsz = sz[r];
ctr.clear();
dfs(r, 0);
rt = ctr[0];
ctr.clear();
dfs(rt, 0);
}
else
{
auto it = find(con[rt].begin(), con[rt].end(), l);
if (it != con[rt].end())
con[rt].erase(it);
it = find(con[rt].begin(), con[rt].end(), r);
if (it != con[rt].end())
con[rt].erase(it);
allsz = sz[rt] - sz[l] - sz[r];
ctr.clear();
dfs(rt, 0);
rt = ctr[0];
ctr.clear();
dfs(rt, 0);
}
}
}
cout << "! " << rt << endl;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
cin >> t;
while (t--)
solve();
}
詳細信息
Test #1:
score: 0
Time Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0 1
output:
? 3 1