#P3379. 【模板】最近公共祖先(LCA)

【模板】最近公共祖先(LCA)

Description

As stated, given a rooted multi-branch tree, find the lowest common ancestor of the specified two nodes.

Input Format

The first line contains three positive integers N,M,SN,M,S, which denote the number of nodes in the tree, the number of queries, and the index of the root node, respectively.

Each of the next N1N-1 lines contains two positive integers x,yx, y, indicating that there is a directly connected edge between node xx and node yy (the testdata guarantees the edges form a tree).

Each of the next MM lines contains two positive integers a,ba, b, asking for the lowest common ancestor of node aa and node bb.

Output Format

Output MM lines, each containing one positive integer, which are the answers to the queries in order.

5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
4
4
1
4
4

Hint

Constraints:

  • For 30%30\% of the testdata, N10N\leq 10, M10M\leq 10.
  • For 70%70\% of the testdata, N10000N\leq 10000, M10000M\leq 10000.
  • For 100%100\% of the testdata, 1N,M5×1051 \leq N,M\leq 5\times10^5, 1x,y,a,bN1 \leq x, y,a ,b \leq N, and it is not guaranteed that aba \neq b.

Sample explanation:

The tree structure is as follows:

  • First query: the lowest common ancestor of 2,42, 4 is 44.
  • Second query: the lowest common ancestor of 3,23, 2 is 44.
  • Third query: the lowest common ancestor of 3,53, 5 is 11.
  • Fourth query: the lowest common ancestor of 1,21, 2 is 44.
  • Fifth query: the lowest common ancestor of 4,54, 5 is 44.

Therefore, the outputs are 4,4,1,4,44, 4, 1, 4, 4 in order.

2021/10/4 testdata update @fstqwq: Added two more sets of testdata to block brute-force jumping.

Translated by ChatGPT 5