题解 P3379 【【模板】最近公共祖先(LCA)】
很多时候我们会遇到要求 (主要是我弱 QAQ ) 。当我们需要求以某个点
首先
但是因为给定了一棵树,所以我们并不需要
然后考虑
然后每次询问
然后不难发现,
不难发现,因为
详见代码:
#include<bits/stdc++.h>
using namespace std;
#define il inline
#define ls(x) t[x].son[0]
#define rs(x) t[x].son[1]
il int read() {
char cc = getchar(); int cn = 0, flus = 1;
while(cc < '0' || cc > '9') { if( cc == '-' ) flus = -flus; cc = getchar(); }
while(cc >= '0' && cc <= '9') cn = cn * 10 + cc - '0', cc = getchar();
return cn * flus;
}
const int N = 5e5 + 5;
struct LCT {
int son[2], fa;
bool mark;
}t[N];
int n, m, s;
bool isroot( int x ) {
return ( ls(t[x].fa) != x ) && ( rs(t[x].fa) != x );
}
void pushmark( int x ) {
if( t[x].mark ) {
t[x].mark = 0, t[ls(x)].mark ^= 1, t[rs(x)].mark ^= 1;
swap( ls(x), rs(x) );
}
}
il void rotate( int x ) {
int f = t[x].fa, ff = t[f].fa, qwq = ( rs(f) == x );
t[x].fa = ff;
if( !isroot(f) ) t[ff].son[rs(ff) == f] = x;
t[t[x].son[qwq ^ 1]].fa = f, t[f].son[qwq] = t[x].son[qwq ^ 1];
t[x].son[qwq ^ 1] = f, t[f].fa = x;
}
int st[N];
il void Splay( int x ) {
int top = 0, now = x; st[++top] = now;
while( !isroot(now) ) st[++top] = ( now = t[now].fa );
while( top ) pushmark( st[top--] );
while( !isroot(x) ) {
int f = t[x].fa, ff = t[f].fa;
if( !isroot(f) ) ( ( rs(ff) == f ) ^ ( rs(f) == x ) ) ? rotate(f) : rotate(x);
rotate( x );
}
}
void access( int x ) {
for( int y = 0; x; y = x, x = t[y].fa ) {
Splay( x ), t[x].son[1] = y;
}
}
void makeroot( int x ) {
access( x ), Splay( x ), t[x].mark ^= 1, pushmark( x );
}
void link( int x, int y ) {
makeroot( x ), t[x].fa = y;
}
int LCA( int x, int y ) {
access( x );
int ans = y;
for( int i = 0; y; ans = i = y, y = t[i].fa ) {
Splay( y ), t[y].son[1] = i;
}
return ans;
}
signed main()
{
n = read(), m = read(), s = read();
int x, y;
for( register int i = 1; i < n; ++ i )
x = read(), y = read(), link( x, y );
makeroot(s);
for( register int i = 1; i <= m; ++ i ) {
x = read(), y = read();
printf("%d\n", LCA( x, y ));
}
return 0;
}