1.倍增法求LCA
struct edge
{
int to;
int next;
};
int tot,head[maxn];
edge e[maxn<<1];
void init()
{
tot=0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
e[tot].to=v;
e[tot].next=head[u];
head[u]=tot;
tot++;
}
struct LCA
{
int dep[maxn];
int fa[maxn][25];
void initlca(int u,int f)
{
dep[u]=dep[f]+1;
for(int i=1;i<=20;i++)fa[u][i]=fa[fa[u][i-1]][i-1];
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].to;
if(to==f)continue;
fa[to][0]=u;
getlca(to,u);
}
}
int lca(int x,int y)
{
if(dep[x]<dep[y])swap(x, y);
for(int i=20;i>=0;i--)if(dep[fa[x][i]]>=dep[y])x=fa[x][i];
if(x==y)return x;
for(int i=20;i>=0;i--)if(fa[x][i]!=fa[y][i])x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
}lca;
应用
1.求树链边上一个值。
Gym - 101889I 询问q次,每次询问带有特定边的MST是多少。
该题容易想到,先求出不带特定边的MST值v,每次询问加入特定边(u,v),如果边在MST边上输出v,如果不在MST上,则去掉(u->lca->v)上 的最大值。
对于树链上的操作,将其lca点找出后,很容易变成线性结构。