QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#779407 | #9570. Binary Tree | windStrider | ML | 1ms | 3596kb | C++20 | 2.3kb | 2024-11-24 18:52:52 | 2024-11-24 18:52:53 |
Judging History
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, v[v[tar].r].sz, size - v[v[tar].l].sz - v[v[tar].r].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);
}
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();
}
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 1ms
memory: 3596kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 0 1 2 0 2 0 0 2
output:
? 2 4 ? 1 5 ! 2 ? 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 0 2 0 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 0 2 1 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 2 2 1 5 4 5 3 1 0 0 0 0 0 0 2 0 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 1 0 5 3 0 5 1 0 0 0 0 4 0 2 2 5 5 0 0 0 0 0 3 0 2 4 2 2
output:
? 8 6 ? 5 4 ? 4 3 ! 4 ? 7 8 ? 3 2 ? 1 4 ! 2 ? 5 8 ? 8 6 ? 4 2 ! 6 ? 3 1 ? 4 5 ! 4 ? 5 6 ? 3 8 ! 3 ? 5 1 ? 1 3 ! 3 ? 1 5 ? 2 4 ? 4 3