题解:P9462 「EZEC-14」终点
Blog
好题!
首先对
考虑 A 性质怎么做。显然
- 若
1, u 同色,则查询(1, u) 的中点v 。可知u 一定在v 的子树中,所以可以递归到v 子树内的子问题。 - 若
1, u 不同色,则查询(2, u) 的中点v 。后面递归到v 子树内也是同理。
容易发现这样的话每次
现在如果 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;
}