using namespace std;
template<typename T> inline bool chkmin(T &a, const T &b){
return a > b ? a = b,
1 :
0; }
template<typename T> inline bool chkmax(T &a, const T &b){
return a < b ? a = b,
1 :
0; }
template<class T> inline T
read()
{
T sum =
0, fg =
1, c = getchar();
while (c <
'0' || c >
'9') {
if (c ==
'-') fg = -
1; c = getchar(); }
while (c >=
'0' && c <=
'9') sum = sum *
10 + c -
'0', c = getchar();
return sum * fg;
}
typedef long long LL;
const
int dmax =
300100, oo =
0x3f3f3f3f;
int N, M;
int begin[dmax],
next[dmax], to[dmax], cnt =
0;
void add(const
int &
x, const
int &
y, const
int &type =
1)
{
to[++cnt] =
y;
next[cnt] = begin[
x];
begin[
x] = cnt;
if (type) add(
y,
x,
0);
}
int lg[dmax];
int rank[dmax], dis[dmax], cur =
0, Dis =
0;
int rm
q[20][dmax];
void dfs(const
int &
x)
{
rank[
x] = ++cur, rm
q[0][cur] =
x;
ER(i,
x)
if (!rank[to[i]])
{
dis[to[i]] = dis[
x] +
1, dfs(to[i]);
rm
q[0][++cur] =
x;
}
}
inline
int Min(const
int &
x, const
int &
y) {
return dis[
x] < dis[
y] ?
x :
y; }
inline void log_init() { REP(i,
1, cur) { lg[i] =
log(i) /
log(
2); debug(
"%d\n", lg[i]); } }
inline void rmq_init()
{
int N = cur;
REP(i,
1, lg[N])
REP(j,
1, N - (
1 << i) +
1)
rm
q[i][j] = Min(rm
q[i - 1][j], rm
q[i - 1][j + (
1 << (i -
1))]);
}
inline
int LCA(
int x,
int y)
{
x = rank[
x],
y = rank[
y];
if (
x >
y) swap(
x,
y);
int k = lg[
y -
x];
return Min(rm
q[k][
x], rm
q[k][
x + (
1 << k) +
1]);
}
inline void init() { dis[
1] =
1, dfs(
1), log_init(), rmq_init(); }
int main()
{
freopen(
"input.txt",
"r", stdin);
freopen(
"output.txt",
"w", stdout);
N =
read<
int>(), M =
read<
int>();
REP(i,
1, N -
1) add(
read<
int>(),
read<
int>());
init();
while (M--)
printf(
"%d\n", LCA(
read<
int>(),
read<
int>()));
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-1310839.html