或许是!<<不是题解>>
2025-08-07 14:19:58
发布于:上海
11阅读
0回复
0点赞
纯他妈左脑缺失指令集,右脑确实运行库,大脑丢包,小脑弹窗.
#include<iostream>
#include<cmath>
#include<queue>
#include<list>
int n,m,s,fa[500001][20],dep[500001],log2n;
std::list<int>map[500001];
std::queue<int>q;
void bfs(...){
q.push(s);
while(q.size()){
for(int i:map[q.front()]){
if(i==*fa[q.front()])continue;
q.push(i),*fa[i]=q.front(),dep[i]=dep[q.front()]+1;
for(int j(1);j<=log2n&&fa[i][j-1];++j)fa[i][j] = fa[fa[i][j-1]][j-1];
}
q.pop();
}
}
int LCA(int x,int y){
if(dep[x]<dep[y])std::swap(x,y);
int dfs(dep[x]-dep[y]);
for(int i(0);i<=log2n&&(dfs>>i);++i)
if((dfs>>i)&1)x = fa[x][i];
if(x == y)return y;
for(int i(log2n+1);i--;)if(fa[x][i]!=fa[y][i])x=fa[x][i],y=fa[y][i];
return *fa[x];//orz
}
int main(){
std::cin.tie(0)->sync_with_stdio(0);
std::cout.tie(0);
int x,y;
std::cin >> n >> m >> s;
log2n = log2(n);
for(int i(1);i<n;++i)std::cin >> x >> y,map[y].push_back(x),map[x].push_back(y);
bfs();
while(m--){
std::cin >> x >> y;//QAQ
std::cout << LCA(x,y) << '\n';//+_+
}
return 0;
}
全部评论 2
点赞
2天前 来自 上海
0给我
2天前 来自 上海
0
有帮助,赞一个