QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#778061 | #9570. Binary Tree | mzyx | RE | 0ms | 0kb | C++20 | 3.6kb | 2024-11-24 12:30:08 | 2024-11-24 12:30:10 |
answer
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
int ask(int u, int v) {
cout << "? " << u << " " << v << endl;
int ret;
cin >> ret;
return ret;
}
void response(int x) {
cout << "! " << x << endl;
}
void solve() {
int n;
cin >> n;
vector<vector<pair<int, int>>> ver(n + 1);
for (int i = 1; i <= n; i++) {
int u, v;
cin >> u >> v;
if (u) {
ver[i].push_back({u, 1});
ver[u].push_back({i, 1});
}
if (v) {
ver[i].push_back({v, 1});
ver[v].push_back({i, 1});
}
}
int root = 1, MaxTree = 1e9; //分别代表重心下标、最大子树大小
vector<int> vis(n + 1), siz(n + 1);
auto get = [&](auto self, int x, int fa, int n) -> void { // 获取树的重心
siz[x] = 1;
int val = 0;
for (auto [y, w] : ver[x]) {
if (y == fa || vis[y] || w == 0) continue;
self(self, y, x, n);
siz[x] += siz[y];
val = max(val, siz[y]);
}
val = max(val, n - siz[x]);
if (val < MaxTree) {
MaxTree = val;
root = x;
}
};
while (true) {
get(get, root, 0, n);
int a = -1, b = -1, c = -1;
for (int i = 0; i < ver[root].size(); i++) {
auto [_, T] = ver[root][i];
if (T == 0) {
continue;
}
if (a == -1) {
a = i;
continue;
}
if (b == -1) {
b = i;
continue;
}
if (c == -1) {
c = i;
continue;
}
}
auto del = [&](int u, int rt) {
for (auto &[x, t] : ver[u]) {
if (x == rt) {
t = 0;
}
}
};
if ((~a) && (~b) && (~c)) {
auto &[u, T1] = ver[root][a];
auto &[v, T2] = ver[root][b];
auto &[w, T3] = ver[root][c];
int ret = ask(u, v);
T1 = 0;
T2 = 0;
del(u, root);
del(v, root);
if (ret == 0) {
T3 = 0;
del(w, root);
root = u;
} else if (ret == 1) {
} else {
T3 = 0;
del(w, root);
root = v;
}
} else if ((~a) && (~b)) {
auto &[u, T1] = ver[root][a];
auto &[v, T2] = ver[root][b];
int ret = ask(u, v);
T1 = 0;
T2 = 0;
del(u, root);
del(v, root);
if (ret == 0) {
root = u;
} else if (ret == 1) {
} else {
root = v;
}
} else if ((~a)){
auto &[u, T] = ver[root][a];
int ret = ask(root, u);
T = 0;
del(u, root);
assert(ret != 1);
if (ret == 2) {
root = u;
}
response(root);
return;
} else {
response(root);
return;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 2
output:
? 1 5 ? 2 3 ! 3