lca倍增写法 全部爆炸(wrong)
查看原帖
lca倍增写法 全部爆炸(wrong)
302750
Main_WF楼主2021/7/21 21:23
#include<bits/stdc++.h>
#define maxn 500010
using namespace std;

struct node{
	int v;
	int nxt;
}e[maxn*2];int k;int head[maxn];

int n,m,depth[maxn],f[maxn][12],lg[maxn];
bool vis[maxn];

template<class type>const void read(type &in)
{
	in=0;
	char ch=getchar();
	while(ch<48||ch>57)ch=getchar();
	while(ch>47&&ch<58)
	{
		in=(in<<1)+(in<<3)+(ch&15);
		ch=getchar();
	}
	return;
} 
 
void add(int u,int v){e[++k].v=v;e[k].nxt=head[u];head[u]=k;}

void dfs(int u)
{
	vis[u] = 1;
	for(int i=head[u]; i ;i=e[i].nxt)
	{
		int v=e[i].v;
		if(!vis[v])
		{
			depth[v] = depth[u] + 1;
			f[v][0] = u;
			for(int j=1; j<=lg[depth[v]] ;j++)
				f[v][j]=f[f[v][j-1]][j-1];
			dfs(v);
		}
	}
}

void reLG()
{
	for(int i=1;i<=n;i++)
		lg[i] = lg[i-1] + (1 << lg[i-1] == i);
	depth[1] = 1;
	dfs(1);
}

int lca(int a,int b)
{
	if(depth[a] < depth[b]) swap(a,b);
	while(depth[a] > depth[b])
		a = f[a][lg[depth[a]-depth[b]]-1];
	if(a==b) return a;
	for(int i=lg[depth[a]]; i>=0 ;i--)
	{
		if(f[a][i] != f[b][i])
		{
			a = f[a][i];
			b = f[b][i];
		}
	}
	return f[a][0];
}

int dist(int a,int b)
{
	int f=lca(a,b);
	return abs(depth[f]-depth[a])+abs(depth[f]-depth[b]);
}

void in()
{
	read(n),read(m);
	for(int i=1; i<=n-1 ;i++)
	{
		int x,y;
		read(x);
		read(y);
		add(x ,y);
		add(y ,x);
	}
	reLG();
	for(int i=1; i<=m ;i++)
	{
		int d1,d2,d3;
		read(d1),read(d2),read(d3); 
		int LCA1 = lca(d1 , d2);
		int LCA2 = lca(d2 , d3);
		int LCA3 = lca(d1 , d3);
		//计算三点分别的代价
		int cost1=abs(depth[LCA1]-depth[d1])+abs(depth[LCA1]-depth[d2])+dist(d3,LCA1);
		int cost2=abs(depth[LCA2]-depth[d2])+abs(depth[LCA2]-depth[d3])+dist(d1,LCA2);;
		int cost3=abs(depth[LCA3]-depth[d1])+abs(depth[LCA3]-depth[d3])+dist(d2,LCA3);;
		if(cost1 <= cost2 && cost1 <= cost3){cout<<LCA1<<' '<<cost1<<'\n';continue;}
		if(cost2 <= cost1 && cost2 <= cost3){cout<<LCA2<<' '<<cost2<<'\n';continue;}
		if(cost3 <= cost1 && cost3 <= cost2){cout<<LCA2<<' '<<cost2<<'\n';continue;}
		
	}
}

int main()
{
	in();
}
2021/7/21 21:23
加载中...