QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#772838 | #9570. Binary Tree | RUOHUI | RE | 0ms | 0kb | C++20 | 3.0kb | 2024-11-22 22:19:05 | 2024-11-22 22:19:06 |
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>());
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);
if(R) adj[i].emplace_back(R), adj[R].emplace_back(i);
}
vector<int> point;
vector<int> vis(n + 1), maxsize(n + 1), size(n + 1);
function<void(int,int)> dfs=[&](int u,int fa)
{
point.emplace_back(u);
maxsize[u] = 0, size[u] = 1;
for(auto& v:adj[u])
{
if(v == fa || vis[u]) continue;
dfs(v, u);
size[u] += size[v];
maxsize[u] = max(maxsize[u], size[v]);
}
};
function<void(int,int)> tag=[&](int u,int fa)
{
vis[u] = true;
for(auto& v:adj[u])
{
if(v == fa || vis[u]) continue;
tag(v, u);
}
};
auto ask=[&](int a, int b)
{
cout <<"? " << a << " " << b << endl;
int ans;
cin >> ans;
return ans;
};
int root = 1;
while(1)
{
vector<int>().swap(point);
dfs(root, 0);
int tot = point.size();
root = 0;
for(auto& u : point)
{
maxsize[u] = max(maxsize[u], tot - size[u]);
if(!root || maxsize[u] < maxsize[root]) root = u;
}
if(tot == 1)
{
cout << "! " << root << endl;
return;
}
vector<int> vec;
for(auto& v:adj[root])
{
if(!vis[v]) vec.emplace_back(v);
}
sort(vec.begin(), vec.end(),[&](int i,int j)
{
return size[i] > size[j];
});
if(vec.size() == 1)
{
if(ask(root, vec[0]) == 0)
{
vis[vec[0]] = true;
}
else vis[root]= true, root = vec[0];
}
else
{
int ans = ask(vec[0], vec[1]);
if(ans == 0)
{
tag(root, vec[0]), root = vec[0];
}
else if(ans == 1)
{
tag(vec[0], root), tag(vec[1], root);
}
else tag(root, vec[1]), root = vec[1];
}
}
}
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
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0 2 0
output:
? 1 3 ? 3 4