#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 , 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 lines contains two positive integers , indicating that there is a directly connected edge between node and node (the testdata guarantees the edges form a tree).
Each of the next lines contains two positive integers , asking for the lowest common ancestor of node and node .
Output Format
Output 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 of the testdata, , .
- For of the testdata, , .
- For of the testdata, , , and it is not guaranteed that .
Sample explanation:
The tree structure is as follows:

- First query: the lowest common ancestor of is .
- Second query: the lowest common ancestor of is .
- Third query: the lowest common ancestor of is .
- Fourth query: the lowest common ancestor of is .
- Fifth query: the lowest common ancestor of is .
Therefore, the outputs are in order.
2021/10/4 testdata update @fstqwq: Added two more sets of testdata to block brute-force jumping.
Translated by ChatGPT 5
京公网安备 11011102002149号