QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#713544 | #9570. Binary Tree | ucup-team1196# | RE | 1ms | 3576kb | C++23 | 2.9kb | 2024-11-05 19:45:00 | 2024-11-05 19:45:01 |
Judging History
answer
#include <bits/stdc++.h>
using namespace std;
#define int long long
int tot = 0;
int query(int u, int v) {
tot--;
assert(tot >= 0);
std::cout << "? " << u << " " << v << std::endl;
int x;
std::cin >> x;
return x;
}
void answer(int x) {
std::cout << "! " << x << std::endl;
}
void solve() {
int n;
std::cin >> n;
tot = std::__lg(n);
std::vector<std::vector<int>> adj(n + 1);
for (int i = 1; i <= n; i++) {
int ls, rs;
std::cin >> ls >> rs;
if (ls) {
adj[i].push_back(ls);
adj[ls].push_back(i);
}
if (rs) {
adj[i].push_back(rs);
adj[rs].push_back(i);
}
}
std::vector<int> vis(n + 1), sz(n + 1), f(n + 1);
f[0] = 1E9;
auto work = [&](auto self, int x, int SZ) -> void {
if (SZ == 1) {
answer(x);
return;
}
auto p = 0;
auto dfs = [&](auto self, int x, int fx) -> void {
sz[x] = 1;
f[x] = 0;
for (auto y : adj[x]) {
if (y == fx || vis[y] == 1) continue;
self(self, y, x);
sz[x] += sz[y];
f[x] = std::max(f[x], sz[y]);
}
f[x] = std::max(f[x], SZ - sz[x]);
if (f[x] < f[p]) {
p = x;
}
};
dfs(dfs, x, 0);
dfs(dfs, p, 0);
// std::cerr << "!!!" << p << std::endl;
std::vector<int> vec;
for (auto y : adj[p]) {
if (vis[y] == 0) {
vec.push_back(y);
}
}
if (vec.size() == 1) {
int a = p, b = vec[0];
int v = query(a, b);
if (v == 0) {
answer(a);
} else if (v == 2) {
answer(b);
} else {
assert(0);
}
} else if (vec.size() == 2) {
int a = vec[0], b = vec[1];
int v = query(a, b);
vis[p] = 1;
if (v == 0) {
self(self, a, sz[a]);
} else if (v == 2) {
self(self, b, sz[b]);
} else {
answer(p);
}
} else if (vec.size() == 3) {
int a = vec[0], b = vec[1];
int v = query(a, b);
if (v == 0) {
self(self, a, sz[a]);
} else if (v == 2) {
self(self, b, sz[b]);
} else {
vis[a] = vis[b] = 1;
self(self, vec[2], sz[vec[2]] + 1);
}
}
};
work(work, 1, n);
}
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int t = 1;
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: 3576kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 1 2 0 2 0 0 2
output:
? 1 5 ? 2 4 ! 3 ? 2 1 ! 1
result:
ok OK (2 test cases)
Test #2:
score: -100
Runtime Error
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 0 2 1
output:
? 2 5 ? 3 8 ? 1 8