最坏1.99s,求优化
查看原帖
最坏1.99s,求优化
1672970
Yishui_LightSky楼主2025/8/28 23:47
#include<iostream>
#include<vector>
#include<math.h>
#include<queue>
using namespace std;
vector<vector<int> >g, st;
vector<int>depth, fath;
int n, m, s;

void dfs(int ind) {//dfs TLE,改用BFS
	queue<int>q;
	q.push(ind);
	fath[ind] = 0;
	int now = 0;
	while (q.size()) {
		now = q.front();
		q.pop();
		depth[now] = depth[fath[now]] + 1;
		for (int i = 0;i < g[now].size();i++) {
			if (g[now][i] != fath[now]) {
				fath[g[now][i]] = now;
				q.push(g[now][i]);
			}
		}
	}
}
int highbit(int num) {
	/*int ans = 0;
	while (num > 1) {
		ans++;
		num = num >> 1;
	}
	return ans;*/
	return floor(log2(num));//注释的超时
}
int toe(int a, int b) {//a.dep<b.dep
	int der = depth[b] - depth[a];
	while (der > 0) {
		int ind = highbit(der);
		int step = 1 << ind;
		b = st[b][ind];
		der -= step;
	}
	return b;
}
void bst(int ind) {
	int step = 1;
	int now = fath[ind];
	st[ind].push_back(now);
	while (1<<step <= depth[ind]) { 
		st[ind].push_back(st[now][step-1]);
		now = st[now][step - 1];
		step++;
	}
	for (int i = 0;i < g[ind].size();i++) {
		if (g[ind][i] != fath[ind])
			bst(g[ind][i]);
	}
}
int find(int a, int b) {
	if (depth[a] > depth[b])swap(a, b);
	b = toe(a, b);
	int ind = highbit(depth[a]);
	while (1) {
		if (a == b)return a;
		if (st[a][ind] == st[b][ind]) {
			if (ind == 0) {
				return st[a][0];
			}
			ind--;
		}
		else {
			a = st[a][ind];
			b = st[b][ind];
			ind = highbit(depth[a]);
		}
	}
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> m >> s;
	g = vector<vector<int> >(n + 1, vector<int>(0));
	st = vector<vector<int> >(n + 1, vector<int>(0));
	for (size_t i = 0; i < n+1; i++)
	{
		st[i].reserve(20);//没有也超时
	}
	depth = vector<int>(n + 1, 0);
	fath = vector<int>(n + 1, 0);
	for (int i = 0;i < n - 1;i++) {
		int u, v;
		cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	dfs(s);
	bst(s);
	while (m--) {
		int u, v;
		cin >> u >> v;
		cout << find(u, v) << endl;
	}
	return 0;
}


2025/8/28 23:47
加载中...