容易发现,无非就是两点距离和 级祖先。
两点距离依赖 lca,而倍增 lca 会 TLE。这时候就有人要说了,那我直接用长链剖分维护 级祖先,用欧拉序和 ST 表维护 lca 不行吗,都是 查询的。这样太复杂了,而且 Deepseek 说数组开太多了,都干到 512 MB+ 了。
但是注意到,重链剖分一样可以维护 lca 和 级祖先,而且预处理复杂度较低,常数也很小( 的时候常数大应该是因为线段树),所以写一个重链剖分就好了。
维护 lca
这个简单,先跳到同一个重链,然后深度小的就是 lca。
维护 级祖先
算出目标深度,然后往上跳到目标深度所在重链,接着由于重链上 dfn 连续,可以直接用当前 dfn 减去距离,得到 lca 的 dfn 后,用一个表查出点的编号。
Code
#include <bits/stdc++.h>
using namespace std;
int n,m,k;
vector<int> g[1000005];
int dep[1000005];
int dfn[1000005];
int fa[1000005];
int sze[1000005],son[1000005];
int top[1000005];
int pos[1000005];
int tot;
void dfs1(int x,int pa)
{
dep[x] = dep[pa]+1;
sze[x] = 1;
fa[x] = pa;
for(auto it:g[x])
{
if(it == pa)continue;
dfs1(it,x);
sze[x] += sze[it];
if(sze[it] > sze[son[x]])
{
son[x] = it;
}
}
return;
}
void dfs2(int x,int pa)
{
dfn[x] = ++tot;
if(son[x])
{
top[son[x]] = top[x];
dfs2(son[x],x);
}
for(auto it:g[x])
{
if(it == pa)continue;
if(it == son[x])continue;
top[it] = it;
dfs2(it,x);
}
}
inline int lca(int x,int y)
{
while(top[x] != top[y])
{
if(dfn[top[x]] < dfn[top[y]])swap(x,y);
x = fa[top[x]];
}
if(dfn[x] > dfn[y])swap(x,y);
return x;
}
inline int djzx(int x,int k)
{
if(k == 0)return x;
int mbdep = dep[x]-k;
while(dep[top[x]] > mbdep)
{
x = fa[top[x]];
}
x = pos[dfn[x]-(dep[x]-mbdep)];
return x;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k;
for(int i = 1;i < n;i++)
{
int x,y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs1(1,0);
top[1] = 1;
dfs2(1,0);
for(int i = 1;i <= n;i++)
{
pos[dfn[i]] = i;
}
int pos = m;
while(k--)
{
int d,t;
cin >> d >> t;
int lcaposd = lca(pos,d);
int dis1 = dep[pos]-dep[lcaposd];
int dis2 = dep[d]-dep[lcaposd];
if(t >= dis1+dis2)
{
pos = d;
cout << pos << " ";
continue;
}
if(t <= dis1)
{
pos = djzx(pos,t);
}
else
{
pos = djzx(d,dis1+dis2-t);
}
cout << pos << " ";
}
return 0;
}