题面大意
- 给定一棵有 个节点的有根二叉树,其中根节点编号为 。
- 树上有一个特殊节点,我们需要实现
int solve(int N, std::vector <int> p),返回特殊节点的编号。 - 可以调用
ask(int x)这个函数,函数返回以x为根节点的子树上书否存在特殊节点。 - 需要在至多调用 次
ask函数的前提下找出这个特殊节点。
解题思路
由于至多调用 次 ask 函数,考虑二分。
首先预处理每一棵子树的大小,然后找到子树大小最接近整棵树大小一半的点,对这个点进行询问。若这个节点的子树包含特殊节点,将根节点更新为这个节点,否则删除这个节点,并更新上方节点的子树大小。这样,我们每一次询问都能排除至少 的点,询问次数至多为 ,时间复杂度为 ,可以通过本题。
代码实现
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using std::vector;
using std::pair;
using std::swap;
using std::queue;
// 大家可以删除注释来方便调试
extern "C" bool ask(int x)
// {
// printf("? %d\n",x);
// fflush(stdout);
// int res;
// scanf("%d",&res);
// return res;
// }
;
vector<int> siz;
struct node
{
int lc,rc;
node()=default;
void add(int u)
{
if(lc)
{
rc=u;
}
else
{
lc=u;
}
}
// 为简化代码,将左子树设为更大的子树。
void upd()
{
if(siz[rc]>siz[lc])
{
swap(lc,rc);
}
}
};
extern "C" int solve(int n,const vector<int> &p)
{
siz.assign(n+1,1);
vector<node> gra(n+1);
vector fa(n+1,-1);
vector rd(n+1,0);
for(int i=2;i<=n;++i)
{
fa[i]=p[i-2];
++rd[fa[i]];
gra[fa[i]].add(i);
}
// BFS 求子树大小
{
queue<int> q;
for(int i=1;i<=n;++i)
{
if(!rd[i])
{
q.emplace(i);
siz[i]=1;
}
}
while(!q.empty())
{
int u=q.front();
q.pop();
gra[u].upd();
if(~fa[u])
{
siz[fa[u]]+=siz[u];
if(!--rd[fa[u]])
{
q.emplace(fa[u]);
}
}
}
}
int root=1;
int tot=n;
while(tot!=1)
{
int now=root;
while(siz[now]>tot>>1)
{
now=gra[now].lc;
}
// 确保 now 为大小最接近 tot/2 的节点
if(abs(siz[fa[now]]-(tot>>1))<abs(siz[now]-(tot>>1)))
{
now=fa[now];
}
if(ask(now))
{
root=now;
tot=siz[now];
}
else
{
int sub=siz[now];
tot-=sub;
for(int i=now;i!=root;i=fa[i])
{
siz[i]-=sub;
gra[fa[i]].upd();
}
}
}
return root;
}
// int main()
// {
// int n;
// scanf("%d",&n);
// vector<int> p(n-1);
// for(int &i:p)
// {
// scanf("%d",&i);
// }
// printf("! %d",solve(n,p));
// }