【模板】倍增LCA

题号:洛谷3379

 %:pragma GCC optimize ("Ofast")
#include<cstdio>
#include<vector>
#include<cctype>
inline int getint() {
int ch;
while(!isdigit(ch=getchar()));
int x=ch^'';
while(isdigit(ch=getchar())) x=(((x<<)+x)<<)+(ch^'');
return x;
}
const int N=,logN=;
std::vector<int> e[N];
int anc[N][logN+]={{}},dep[N];
inline void add_edge(const int u,const int v) {
e[u].push_back(v);
e[v].push_back(u);
}
void dfs(const int x,const int parent,const int depth) {
anc[x][]=parent,dep[x]=depth;
for(int i=;i<=logN;i++) {
anc[x][i]=anc[anc[x][i-]][i-];
}
for(unsigned int i=;i<e[x].size();i++) {
if(e[x][i]==parent) continue;
dfs(e[x][i],x,depth+);
}
}
inline void swap(int &a,int &b) {
int t;
t=a;
a=b;
b=t;
}
int LCA(int a,int b) {
if(dep[a]<dep[b]) swap(a,b);
for(int i=logN;i>=;i--) {
if(dep[a]-(<<i)>=dep[b]) a=anc[a][i];
}
if(a==b) return a;
for(int i=logN;i>=;i--) {
if(anc[a][i]&&anc[a][i]!=anc[b][i]) {
a=anc[a][i];
b=anc[b][i];
}
}
return anc[a][];
}
int main() {
int n=getint(),m=getint(),s=getint();
for(int i=;i<n;i++) add_edge(getint(),getint());
dfs(s,,);
while(m--) printf("%d\n",LCA(getint(),getint()));
return ;
}
上一篇:【动态规划】洛谷P1006传纸条


下一篇:jupyter notebook的路径