【模板】ST表求LCA

算法流程:
1.dfs分别求出第几次访问的是哪个点,深度是多少以及每个点第一次被访问的序号(这里不是一般意义上的DFS序)。

2.ST表求询问的两点序间的深度最小的点是哪个点。

 

代码:

#include <bits/stdc++.h>
using namespace std;

const int Max=200005;
int n,m,size,tot;
int first[Max],depth[Max],Log[Max];
int id[Max],dis[Max],num[Max];
int f[Max][20];
struct shu{int to,next,len;};
shu edge[Max];

inline int get_int()
{
	int x=0,f=1;
	char c;
	for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
	if(c=='-') f=-1,c=getchar();
	for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
	return x*f;
}
inline void print(int x)
{
	if(x>9) print(x/10);
	putchar('0'+x%10);
}

inline void build(int x,int y,int z)
{
	edge[++size].next=first[x];
	first[x]=size;
	edge[size].to=y,edge[size].len=z;
}

inline void dfs(int point,int fa,int dep)
{
	num[point]=++tot;
	id[tot]=point,depth[tot]=dep;
	for(int u=first[point];u;u=edge[u].next)
	{
	  int to=edge[u].to;
	  if(fa==to) continue;
	  dis[to]=dis[point]+edge[u].len;
	  dfs(to,point,dep+1);
	  id[++tot]=point,depth[tot]=dep;
	}
}

inline void pre()
{
	Log[0]=-1; //保证log[1]为0 
	for(int i=1;i<=tot;++i) Log[i]=Log[i>>1]+1;
	for(int i=1;i<=tot;++i) f[i][0]=i;
	for(int j=1;(1<<j)<=tot;++j)
	  for(int i=1;i+(1<<j)-1<=tot;++i)
	  {
	  	int x=f[i][j-1],y=f[i+(1<<j-1)][j-1];
	  	if(depth[x] < depth[y]) f[i][j]=x;
	  	else f[i][j]=y;
	  }
}

inline int LCA(int x,int y)
{
	if(num[x]>num[y]) swap(x,y);
	int s=num[x],t=num[y],len=Log[t-s+1];
	if(depth[f[s][len]] < depth[f[t-(1<<len)+1][len]]) return id[f[s][len]];
	else return id[f[t-(1<<len)+1][len]];
}

inline void solve()
{
	while(m--)
	{
	  int x=get_int(),y=get_int();
	  print(dis[x]+dis[y]-2*dis[LCA(x,y)]),putchar('\n');
	}
}

int main()
{
	n=get_int(),m=get_int();
	for(int i=1;i<n;i++)
	{
	  int x=get_int(),y=get_int(),z=get_int();
	  build(x,y,z),build(y,x,z);
	}
	dfs(1,0,0);
	pre();
	solve();
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值