为啥本地编译可以,洛谷失败啊,调半天
  • 板块学术版
  • 楼主xiaozhuo
  • 当前回复5
  • 已保存回复5
  • 发布时间2023/7/20 20:34
  • 上次更新2023/11/3 08:34:30
查看原帖
为啥本地编译可以,洛谷失败啊,调半天
355377
xiaozhuo楼主2023/7/20 20:34
#include<bits/stdc++.h>
using namespace std;
#define N 500010
int cont, head[N], next[N], val[N], d[N], f[N][25], t;
void add(int u, int v)
{
	val[++ cont] = v;
	next[cont] = head[u];
	head[u] = cont;
}
int n, p, rt;
queue<int> q;
void bfs()
{
	q.push(rt);
	d[rt] = 1;
	while(q.size())
	{
		int now = q.front();
		q.pop();
		for(int i = head[now];i;i = next[i])
		{
			int s = val[i];
			if(d[s]) continue;
			d[s] = d[now] + 1;
			f[s][0] = now;
			for(int j = 1;j <= 20;j ++) f[s][j] = f[f[s][j - 1]][j - 1];
			q.push(s);
		}
	}
}
int lac(int x, int y)
{
	if(d[x] > d[y]) swap(x, y);
	for(int j = 20;j >= 0;j --)
		if(d[f[y][j]] >= d[x]) y = f[y][j];
	if(x == y) return y;
	for(int j = 20;j >= 0;j --)
		if(f[x][j] != f[y][j]) x = f[x][j], y = f[y][j];
	return f[x][0];
}
int main()
{
	cin >> n >> p >> rt;
	int a, b;
	for(int i = 1;i < n;i ++)
	{
		cin >> a >> b;
		add(a, b);
		add(b, a);
	}
	bfs();
	for(int i = 1;i <= p;i ++)
	{
		cin >> a >> b;
		int ans = lac(a, b);
		cout << ans << "\n";
	}
	return 0;
}
2023/7/20 20:34
加载中...