QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#779427 | #9570. Binary Tree | windStrider | ML | 0ms | 0kb | C++20 | 2.4kb | 2024-11-24 19:00:12 | 2024-11-24 19:00:14 |
answer
#include <bits/stdc++.h>
constexpr int inf = 0x3f3f3f3f;
struct nd
{
int v, l, r, f, sz;
nd() : v(0), l(0), r(0), f(0), sz(0) { }
};
void bfs(std::vector<nd>& v, int& rt)
{
int size = v[rt].sz;
std::queue<int> q;
q.emplace(rt);
std::function<void(int, int)>update = [&](int x, int val) -> void
{
v[x].sz -= val;
while (v[x].f) x = v[x].f, v[x].sz -= val;
};
int obj = 0, mn = inf;
while (q.size())
{
int tar = q.front();
q.pop();
int mx = std::max({ v[v[tar].l].sz + 1, v[v[tar].r].sz + 1, size - v[tar].sz });
if (mx < mn) mn = mx, obj = tar;
if (v[tar].l) q.emplace(v[tar].l);
if (v[tar].r) q.emplace(v[tar].r);
}
std::cout << obj << "\n";
if (v[obj].l && v[obj].r)
{
std::cout << "? " << v[obj].l << " " << v[obj].r << std::endl;
int bk;
std::cin >> bk;
if (bk == 1) v[obj].l = 0, v[obj].r = 0, update(obj, v[obj].sz);
else if (bk == 0) rt = v[obj].l, v[rt].f = 0;
else rt = v[obj].r, v[rt].f = 0;
}
else if (v[obj].l)
{
std::cout << "? " << obj << " " << v[obj].l << std::endl;
int bk;
std::cin >> bk;
if (bk == 0) v[obj].l = 0, update(obj, v[obj].sz);
else rt = v[obj].l, v[rt].f = 0;
}
else if (v[obj].r)
{
std::cout << "? " << obj << " " << v[obj].r << std::endl;
int bk;
std::cin >> bk;
if (bk == 0) v[obj].r = 0, update(obj, v[obj].sz);
else rt = v[obj].r, v[rt].f = 0;
}
}
void solve()
{
int n;
std::cin >> n;
std::vector<nd> v(n + 1);
for (int i = 1; i <= n; ++i)
{
int l, r;
std::cin >> l >> r;
v[i].v = i, v[i].l = l, v[i].r = r;
v[l].f = i, v[r].f = i;
}
int rt = 1;
while (v[rt].f != 0) rt = v[rt].f;
std::function<int(int)>dfs = [&](int t) -> int
{
int v1 = 0, v2 = 0;
if (v[t].l) v1 = dfs(v[t].l);
if (v[t].r) v2 = dfs(v[t].r);
v[t].sz += v1 + v2;
return v[t].sz + 1;
};
dfs(rt);
while (v[rt].sz) bfs(v, rt);
std::cout << "! " << rt << std::endl;
}
int main()
{
int t;
std::cin >> t;
while (t--)
{
solve();
}
}
詳細信息
Test #1:
score: 0
Memory Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0
output:
2 ? 1 5