luogu#P5002. 专心OI - 找祖先

专心OI - 找祖先

Background

Imakf is a beginner. He has recently learned LCA. He saw a game in the mobile App Store that is also called LCA, so he downloaded it.

Problem Description

This game gives you a tree with NN nodes, where the root is RR. The system will select MM nodes P1,P2PMP_1,P_2 \cdots P_M, and asks Imakf to answer how many ordered pairs of nodes (ui,vi)(u_i, v_i) have their lowest common ancestor equal to PiP_i. Imakf is a beginner. Even though he has learned LCA, he still cannot solve it, so he has to ask you for help.

Input Format

The first line contains three integers N,R,MN, R, M.

Then N1N - 1 lines follow, each containing two numbers a,ba, b, indicating that there is an edge between aa and bb.

Then 11 line follows, containing MM numbers, indicating PiP_i.

It is guaranteed that the given edges form a tree.

Output Format

Output MM lines in total. Each line contains one number. The number on line ii indicates how many ordered pairs of nodes (ui,vi)(u_i, v_i) have their lowest common ancestor equal to PiP_i.

7 1 3
1 2
1 3
2 4
2 5
3 6
3 7
1 2 4
31
7
1

Hint

The tree of Sample 1 is shown in the figure below:

For Query 1 $~(1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (1,7) (2,1) (2,3) (2,6) (2,7) (3,1) (3,2) (3,4) (3,5) (4,1) (4,3)$

$(4,6) (4,7) (5,1) (5,3) (5,6) (5,7) (6,1) (6,2) (6,4) (6,5) (7,1) (7,2) (7,4) (7,5)$ there are 3131 ordered pairs in total.

For Query 2 (2,2)(2,4)(2,5)(4,2)(4,5)(5,2)(5,4)(2,2) (2,4) (2,5) (4,2) (4,5) (5,2) (5,4) there are 77 ordered pairs in total.

For Query 3 (4,4)(4,4) there is 11 ordered pair in total.

Constraints: 1RN100001 \le R \le N \leq 10000, 0M500000 \le M \leq 50000.

Translated by ChatGPT 5