模板集合(持续更新)

倍增求\(LCA\)

int fa[N][21],dep[N];
void dfs(int u,int f) {
	dep[u] = dep[f]+1; 
	fa[u][0] = f;
	for(int i = 1;(1<<i) <= dep[u]; ++i) fa[u][i] = fa[fa[u][i-1]][i-1];
	for(int i = head[u]; i; i = e[i].nxt) {
		int v = e[i].v; if(v == f) continue;
		dfs(v,u);
	}
}

int Q_lca(int x,int y) {
	if(dep[x] < dep[y]) swap(x,y);
	int d = dep[x]-dep[y];
	for(int i = 0;(1<<i) <= d; ++i) {
		if(d&(1<<i)) x = fa[x][i];
	}
	if(x == y) return x;
	for(int i = 20;i >= 0; --i) {
		if(fa[x][i] == fa[y][i]) continue;//debug [i] -> [0]
		x = fa[x][i]; y = fa[y][i];
	}
	return fa[x][0];
}
posted @ 2019-09-18 11:57  陈星卿  阅读(162)  评论(0编辑  收藏  举报