题解 P5903 【【模板】树上 k 级祖先】
博客不一定食用更佳 题目在这
update 2020.12.26 对不起给管理添麻烦了,修了图上文字的错误和算法的最后一步的错误,讲解了长链剖分
基础知识:
树上倍增,可以去 LCA 模板学;
重链剖分
我们的目标是预处理
- 假设你刚学循环,你看到这道题会怎么做?暴力往上跳,
\mathcal O(n) 预处理(读入),\mathcal O(n) 查询。 - 假设你刚学数组,你看到这道题会怎么做?每个点存祖先,
\mathcal O(n^2) 预处理,\mathcal O(1) 查询,优化了 1 的查询,但增加了预处理的复杂度。 - 假如你刚学树上倍增,你看到这道题会怎么做?记
fa_{i,j} 表示i 的2^j 倍祖先,类似 LCA,\mathcal O(n\log n) 预处理,\mathcal O(\log n) 查询。优化了 1 的查询,增加了预处理的复杂度,但是在可接受范围内。 - 假如你刚学重链剖分或者长链剖分,你看到这道题会怎么做?剖一下,往上跳,发现链顶过了就暴力跳(倍增跳也可以,但由于与 3 差不多,这里不再说了)。
\mathcal O(n) 预处理,\mathcal O(n) 查询。
发现 2 优化了 1
记点
我们发现只会查询链顶的上祖先,于是改为只对链顶记祖先。但是空间和预处理的复杂度仍然可能会达到
我们发现用 3 进行预处理后,跳
(看不懂别走,下面有图。)
因为
如果没懂,看图会更清楚一些:
于是,我们增加一个东西,记录每个链顶往上 链长个和往下 链长个节点。预处理时间复杂度为
代码:
#include<bits/stdc++.h>
using namepace std;
vector<int>g[500010],up[500010],down[500010];//g存树,up表示向上的节点,down类似,必须要用vector存
int binh[500010],dep[500010],h[500010],hson[500010],tp[500010],fa[500010][20];//binh[i]表示i的最高位的位数,也就是log2(i),dep是深度,h是高度,hson是长儿子(类似重链剖分),tp是链顶,fa是倍增
unsigned int s;//题目中给的种子
inline int read()//快读
{
char c=getchar();
int x=0;
while(c<'0'||c>'9')
c=getchar();
while(c>='0'&&c<='9')
{
x=(x<<3)+(x<<1)+c-'0';
c=getchar();
}
return x;
}
inline void write(long long x)//快写
{
if(!x)
{
putchar('0');
return;
}
int sta[20],tp=0;
while(x)
{
sta[++tp]=x%10;
x/=10;
}
while(tp)
putchar(sta[tp--]+'0');
}
inline unsigned int get(unsigned int x)//题目中给的随机函数
{
x^=x<<13;
x^=x>>17;
x^=x<<5;
return s=x;
}
void dfs(int x,int f)//类似重链剖分,第一次dfs,求dep,fa,hson,h
{
dep[x]=dep[f]+1;
fa[x][0]=f;
for(int i=1;i<20;i++)
fa[x][i]=fa[fa[x][i-1]][i-1];
h[x]=-1;
for(int i=0;i<g[x].size();i++)
{
dfs(g[x][i],x);
if(h[g[x][i]]>h[x])
{
hson[x]=g[x][i];
h[x]=h[g[x][i]];
}
}
h[x]++;
if(!h[x])//如果是叶子
h[x]=1;
}
void dfs2(int x,int ttp)//类似重链剖分,第二次dfs,求up,down,tp
{
down[ttp].push_back(x);
tp[x]=ttp;
if(g[x].empty())
return;
dfs2(hson[x],ttp);
for(int i=0;i<g[x].size();i++)
if(g[x][i]!=hson[x])
{
up[g[x][i]].push_back(g[x][i]);
for(int j=1;j<=h[g[x][i]];j++)
up[g[x][i]].push_back(fa[up[g[x][i]].back()][0]);
dfs2(g[x][i],g[x][i]);
}
}
int main()
{
int n=read(),q=read(),i,root,x,k,lastans=0;
long long out=0;
cin>>s;
for(i=1;i<=n;i++)
{
x=read();
if(!x)
root=i;
else
g[x].push_back(i);
binh[i]=log2(i);
}
dfs(root,root);
up[root].push_back(root);
for(i=1;i<=h[root];i++)
up[root].push_back(fa[up[root].back()][0]);
dfs2(root,root);
for(i=1;i<=q;i++)
{
x=(get(s)^lastans)%n+1;
k=(get(s)^lastans)%dep[x];
if(!k)//0级祖先要特判
{
lastans=x;
out^=1ll*i*x;
continue;
}
int tod=dep[x]-k;//目标深度
x=tp[fa[x][binh[k]]];//先跳一步
int tpd=dep[x];//目前深度
if(tpd<tod)
x=down[x][tod-tpd];
else
x=up[x][tpd-tod];
lastans=x;
out^=1ll*i*x;
}
write(out);
return 0;
}
觉得好就点个赞吧,有问题或者建议欢迎在评论区提出来。