好题!
首先对 查询 ,可以确定树的二分图染色。
考虑 A 性质怎么做。显然 的父亲一定是 ,于是我们可以依次确定 的父亲。具体而言,假设当前要确定的是 的父亲:
- 若 同色,则查询 的中点 。可知 一定在 的子树中,所以可以递归到 子树内的子问题。
- 若 不同色,则查询 的中点 。后面递归到 子树内也是同理。
容易发现这样的话每次 的距离会变为原来的一半,所以需要用 次操作。
现在如果 A 性质不成立了,我们就要想办法将 A 性质的做法转化一下。
先是要求出一个与 相邻的节点,这样才能在后面处理与 异色的点。该如何求出这个相邻的点?结论是:我们在确定树的二分图染色后,跳跃到异色点的步数最多的一条路径上的异色点就是与 相邻的节点。证明可以考虑对 之间的距离做质因数分解,容易发现如果存在一个非 质因子,则替换为 是一定最优的,到最后就一定是 的形式,即与 相邻。
求出相邻点之后就是好做的了,我们仿照上文的思路,用这个类似整体二分的方法逐步确定所有点的父亲。这个可以用 BFS 实现,只要把当前局面下已确定父亲的点全部丢进队列里即可。遇到需要查询未确定父亲的节点时,直接把询问挂在那个点上,等它出队的时候再处理即可。
操作次数大概是 级别。
#include <bits/stdc++.h>
#define fi first
#define se second
#define eb(x) emplace_back(x)
#define pb(x) push_back(x)
#define lc(x) (tr[x].ls)
#define rc(x) (tr[x].rs)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
typedef __int128 i128;
using pi = pair<int, int>;
const int N = 10005;
map<pi, int> ans;
int query(int x, int y)
{
if(ans.count({x, y})) return ans[{x, y}];
cout << "? " << x << " " << y << endl;
int res;
cin >> res;
ans[{x, y}] = res;
return res;
}
int tid, n, fa[N], col[N], dep[N];
vector<int> g[N], qs[N];
void dfs(int u)
{
for(auto v : g[u])
{
dfs(v);
dep[u] = max(dep[u], dep[v] + 1);
}
}
int main()
{
cin >> tid >> n;
col[1] = 1;
for(int i = 2; i <= n; i++)
{
col[i] = query(1, i);
if(col[i] == 0) g[1].push_back(i);
else
{
g[col[i]].push_back(i);
col[i] = 1;
}
}
dfs(1);
int m = 2;
for(int i = 3; i <= n; i++)
if(dep[i] > dep[m])
m = i;
queue<int> q;
q.push(1); q.push(m);
fa[1] = m; fa[m] = 1;
for(int i = 2; i <= n; i++)
if(i != m)
qs[1].push_back(i);
while(!q.empty())
{
int u = q.front();
q.pop();
for(auto v : qs[u])
{
if(col[u] == col[v])
qs[query(u, v)].push_back(v);
else
{
int res = query(fa[u], v);
if(res == u) fa[v] = u, q.push(v);
else qs[res].push_back(v);
}
}
}
cout << "!" << endl;
for(int i = 2; i <= n; i++) cout << i << " " << fa[i] << endl;
return 0;
}