QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#751500 | #9570. Binary Tree | zsofustb | RE | 0ms | 0kb | C++20 | 3.8kb | 2024-11-15 19:10:28 | 2024-11-15 19:10:29 |
answer
#include <bits/stdc++.h>
using i64 = long long;
struct Node {
int id, sz;
};
void solve() {
int n;
std::cin >> n;
std::vector<std::vector<Node>> adj(n + 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= 2; j++) {
int x;
std::cin >> x;
if (x != 0) {
adj[i].push_back({x, 0});
adj[x].push_back({i, 0});
}
}
}
auto query = [&](int a, int b) -> int {
std::cout << "? " << a << " " << b << std::endl;
int res;
std::cin >> res;
return res;
};
int siz = n, root = 1;
int a, b, target;
auto dfs = [&](auto self, int u, int fa) -> int {
int res = 1;
for (auto &t: adj[u]) {
int v = t.id;
if (v != fa) {
t.sz = self(self, v, u);
res += t.sz;
}
}
std::vector<int> vec;
for (auto &t: adj[u]) {
int v = t.id;
vec.push_back(t.sz);
if (v == fa) {
t.sz = siz - res;
}
}
if (vec.size() == 3) {
int mx = *std::max_element(vec.begin(), vec.end());
if (mx <= siz - mx) {
target = u;
if (adj[u][0].sz == mx) {
a = adj[u][0].id;
b = adj[u][1].id;
} else {
a = adj[u][1].id;
b = adj[u][2].id;
}
}
} else if (vec.size() == 2) {
if (abs(vec[0] - vec[1]) <= 1) {
target = u;
a = vec[0];
b = vec[1];
}
}
return res;
};
while (siz >= 3) {
dfs(dfs, root, -1);
int t = query(a, b);
if (t == 0) {
for (auto it: adj[target]) {
if (it.id == a) {
siz = it.sz;
}
}
for (auto it = adj[a].begin(); it != adj[a].end();) {
if (it->id == target) {
adj[a].erase(it);
break;
} else {
it++;
}
}
root = a;
} else if (t == 1) {
for (auto it: adj[target]) {
if (it.id == a || it.id == b) {
siz -= it.sz;
}
}
for (auto it = adj[target].begin(); it != adj[target].end();) {
if (it->id == a || it->id == b) {
adj[target].erase(it);
} else {
it++;
}
}
root = target;
} else {
std::swap(a, b);
for (auto it: adj[target]) {
if (it.id == a) {
siz = it.sz;
}
}
for (auto it = adj[a].begin(); it != adj[a].end();) {
if (it->id == target) {
adj[a].erase(it);
break;
} else {
it++;
}
}
root = a;
}
}
if (siz == 2) {
a = target, b = adj[target][0].id;
int t = query(a, b);
if (t == 0) {
std::cout << "! " << a << std::endl;
} else {
std::cout << "! " << b << std::endl;
}
} else {
std::cout << "! " << target << std::endl;
}
std::cout << std::endl;
}
int main() {
// std::ios::sync_with_stdio(false);
// std::cin.tie(nullptr), std::cout.tie(nullptr);
int T;
std::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 2 0
output:
? 5 3 ? 2 1 ! 2