T了一个点,有没有大佬看看什么问题!!
查看原帖
T了一个点,有没有大佬看看什么问题!!
385341
dyznb楼主2021/5/17 19:57
#include<bits/stdc++.h>
using namespace std;
int n,m,s;
int cot;
int head[1000004];
struct edag
{
	int s,e,w,next;
}eg[10000005];
int fa[10000005];
int dep[10000005];
void add(int s,int e)
{
	eg[cot].e=e;
	eg[cot].s=s;
	eg[cot].next=head[s];
	head[s]=cot++;
}
void dfs(int root)
{
	
	for(int i=head[root];i!=-1;i=eg[i].next)
	{
		if(dep[eg[i].e])
			continue;
		dep[eg[i].e]=dep[root]+1;
		fa[eg[i].e]=root;
		dfs(eg[i].e);
	}
}
int lca(int a,int b)
{
	if(dep[a]<dep[b])
	swap(a,b);
	while(dep[a]>dep[b])
	{
		a=fa[a];
	}
	while(a!=b)
	{
		a=fa[a];
		b=fa[b];
	}
	return a;
}
int main()
{
	memset(head,-1,sizeof(head));
	cin>>n>>m>>s;
	dep[s]=1;
	for(int i=1;i<=n-1;i++)
	{
		int st,ed;
		cin>>st>>ed;
		add(st,ed);
		add(ed,st);
	}
	dfs(s);
	for(int i=1;i<=m;i++)
	{
		int a,b;
		cin>>a>>b;
		cout<<lca(a,b)<<endl;
	}
	return 0;
}
2021/5/17 19:57
加载中...