QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#795932 | #9570. Binary Tree | nhuang685 | RE | 0ms | 0kb | C++23 | 2.8kb | 2024-12-01 04:44:55 | 2024-12-01 04:44:55 |
answer
/**
* @author n685
* @brief
* @date 2024-11-30 15:19:48
*
*
*/
#include "bits/stdc++.h"
#ifdef LOCAL
#include "dd/debug.h"
#else
#define dbg(...) 42
#define dbg_proj(...) 420
#define dbg_rproj(...) 420420
void nline() {}
void bar() {}
void start_clock() {}
void end_clock() {}
#endif
namespace rs = std::ranges;
namespace rv = std::views;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
int query(int u, int v) {
std::cout << "? " << u + 1 << ' ' << v + 1 << std::endl;
int t;
std::cin >> t;
return t;
}
void solve() {
int n;
std::cin >> n;
std::vector<std::vector<int>> adj(n);
for (int i = 0; i < n; ++i) {
int x, y;
std::cin >> x >> y;
--x;
--y;
if (x != -1) {
adj[i].push_back(x);
adj[x].push_back(i);
}
if (y != -1) {
adj[i].push_back(y);
adj[y].push_back(i);
}
}
std::vector<int> sub(n);
auto comp = [&](auto&& self, int node, int par) -> void {
sub[node] = 1;
for (int i : adj[node]) {
if (i == par) {
continue;
}
self(self, i, node);
sub[node] += sub[i];
}
};
auto cent = [&](auto&& self, int node, int par) -> int {
for (int i : adj[node]) {
if (i != par && 2 * sub[i] > sub[node]) {
return self(self, i, node);
}
}
return node;
};
comp(comp, 0, -1);
int node = cent(cent, 0, -1);
while (std::ssize(adj[node]) > 1) {
comp(comp, node, -1);
if (std::ssize(adj[node]) == 2) {
int u = adj[node][0], v = adj[node][1];
int t = query(u, v);
if (t == 1) {
break;
}
if (t == 0) {
std::erase(adj[node], v);
node = u;
} else {
std::erase(adj[node], u);
node = v;
}
} else {
std::array<int, 3> ord{adj[node][0], adj[node][1], adj[node][2]};
if (sub[ord[0]] < sub[ord[1]]) {
std::swap(ord[0], ord[1]);
}
if (sub[ord[1]] < sub[ord[2]]) {
std::swap(ord[1], ord[2]);
}
if (sub[ord[0]] < sub[ord[1]]) {
std::swap(ord[0], ord[1]);
}
int t = query(ord[0], ord[1]);
if (t == 0) {
std::erase(adj[ord[0]], node);
node = ord[0];
} else if (t == 1) {
std::erase(adj[node], ord[0]);
std::erase(adj[node], ord[1]);
} else {
std::erase(adj[ord[1]], node);
node = ord[1];
}
}
comp(comp, node, -1);
node = cent(cent, node, -1);
}
std::cout << "! " << node + 1 << std::endl;
}
int main() {
#ifndef LOCAL
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
#endif
int t;
std::cin >> t;
for (int i = 0; i < t; ++i) {
dbg(i + 1);
solve();
bar();
}
}
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
output:
? 3 1 ! 2