蒟蒻又来复习模板了。还WA了两次
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long
#define ON_DEBUG
#ifdef ON_DEBUG
#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x) cout << #x << " = " << x << endl
#define Pause() system("pause")
#else
#define D_e_Line ;
#endif
struct ios{
template<typename ATP>ios& operator >> (ATP &x){
x = 0; int f = 1; char c;
for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
x*= f;
return *this;
}
}io;
using namespace std;
const int N = 500007;
struct Edge{
int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
e[++cntEdge] = (Edge){head[u], v}, head[u] = cntEdge;
}
int f[N][22], lg[N], dep[N];
inline void DFS(int u, int fa){
dep[u] = dep[fa] + 1, f[u][0] = fa;
for(register int i = 1; (1 << i) <= dep[u]; ++ i){
f[u][i] = f[f[u][i - 1]][i - 1];
}
for(register int i = head[u]; i; i = e[i].nxt){
int v = e[i].pre;
if(v == fa) continue;
DFS(v, u);
}
}
inline int LCA(int x, int y){
if(dep[x] < dep[y]) Swap(x, y);
while(dep[x] > dep[y]){
x = f[x][lg[dep[x] - dep[y]] - 1];
}
if(x == y) return x;
nR(k,lg[dep[x]] - 1,0){
if(f[x][k] != f[y][k]){
x = f[x][k];
y = f[y][k];
}
}
return f[x][0];
}
int main(){
int n, Ques, root;
io >> n >> Ques >> root;
R(i,1,n-1){
int u, v;
io >> u >> v;
add(u, v);
add(v, u);
}
//log(n) + 1
R(i,1,n)
lg[i] = lg[i-1] + ((1 << lg[i - 1]) == i);
DFS(root,0);
while(Ques--){
int x, y;
io >> x >> y;
printf("%d\n", LCA(x, y));
}
return 0;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章