QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#770945 | #9570. Binary Tree | RUOHUI | TL | 0ms | 0kb | C++20 | 3.2kb | 2024-11-22 03:57:21 | 2024-11-22 03:57:21 |
answer
#include "bits/stdc++.h"
#define int long long
#define ull unsigned long long
#define PII pair<int, int>
#define TIII tuple<int, int, int>
#define LL __int128
#define eps 1e-6
using namespace std;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
constexpr int N = 2e6 + 10, M = 2e6 + 10, mod = 1e9 + 7, inf = 1e18;
int n, m;
void solve()
{
cin >> n;
vector<vector<int>> adj(n + 1, vector<int>());
vector<int> size(n + 1), p(n + 1);
vector<int> deg(n + 1);
for (int i = 1; i <= n; i++)
{
int L, R;
cin >> L >> R;
if (L)
{
adj[i].emplace_back(L), adj[L].emplace_back(i);
deg[i]++, deg[L]++, p[L] = i;
}
if (R)
{
adj[i].emplace_back(R), adj[R].emplace_back(i);
deg[i]++, deg[R]++, p[R] = i;
}
}
auto get = [&](int u, int n)
{
int root = 0;
function<void(int, int)> dfs1 = [&](int u, int fa)
{
size[u] = 1, p[u] = fa;
bool pass = true;
for (auto &v: adj[u])
{
if (v == fa) continue;
dfs1(v, u);
size[u] += size[v];
if (size[v] > n / 2) pass = false;
}
if (n - size[u] > n / 2) pass = false;
if (pass) root = u;
};
dfs1(u, p[u]);
return root;
};
auto ask = [&](int a, int b) -> int
{
int ans;
cout << "? " << a << " " << b << endl;
cin >> ans;
return ans;
};
int pre = 1;
for (int i = 1; i <= n; i++)
{
if (!p[i]) pre = i;
}
while (1)
{
int root = get(pre, size[pre]);
if (deg[root] == 1)
{
if (ask(root, adj[root][0]) == 0)
{
cout << "! " << root << endl;
return;
}
else
{
cout << "! " << adj[root][0] << endl;
return;
}
}
if (deg[root] == 2)
{
int a = adj[root][0], b = adj[root][1];
int ans = ask(a, b);
if (ans == 0)
{
cout << "! " << root << endl;
return;
}
pre = (ans == 0 ? a : b);
}
if (deg[root] == 3)
{
vector<int> vec{adj[root][0], adj[root][1], adj[root][3]};
sort(vec.begin(), vec.end(), [&](int i, int j)
{
return size[i] > size[j];
});
int a = vec[0], b = vec[1];
int ans = ask(a, b);
if (ans == 0)
{
cout << "! " << root << endl;
return;
}
pre = (ans == 0 ? a : b);
}
}
}
signed main()
{
std::ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
cout << fixed << setprecision(2);
#ifndef ONLINE_JUDGE
freopen("in.txt", "rt", stdin);
freopen("out.txt", "wt", stdout);
#endif
int Cases = 1;
cin >> Cases;
while (Cases--)
{
solve();
}
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Time Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0 2
output:
? 4 3 ! 3