#P3248. [HNOI2016] 树

    ID: 2297 远端评测题 2000ms 250MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>2016各省省选湖南最近公共祖先,LCA树套树主席树

[HNOI2016] 树

Description

Little A wants to build a very large tree, but his materials are limited, so he uses a small trick. Initially, Little A has a tree with NN nodes, numbered 1,2,...,N1, 2, ..., N, where node 11 is the root; we call this the "template tree". Little A decides to construct a large tree based on this template tree. The construction proceeds as follows:

  1. Copy the template tree as the initial large tree.

  2. Repeat steps (2.1)–(2.3) MM times.

(2.1) Choose two integers a,ba, b, where 1aN1 \leq a \leq N, 1b1 \leq b \leq the current number of nodes in the large tree.

(2.2) Copy the subtree of the template tree rooted at node aa, and attach it under node bb in the large tree (that is, after copying, the subtree rooted at node aa from the template tree becomes a subtree of node bb in the large tree).

(2.3) Renumber the newly added nodes in the large tree according to their order in the template tree. For example, suppose the large tree has LL nodes before step (2.2), and the subtree rooted at aa in the template tree has CC nodes. Then the CC newly added nodes will be numbered L+1,L+2,...,L+CL+1, L+2, ..., L+C in the large tree; the relative order of these CC node numbers in the large tree is consistent with the order of the corresponding CC nodes in the template tree. An example is given below. Suppose the template tree is as follows:

According to step (1), the initial large tree is the same as the template tree.

In step (2.1), suppose we choose a=4,b=3a=4, b=3. After performing steps (2.2) and (2.3), the new large tree is as shown below:

Now he asks you for the distances between some pairs of nodes in the tree.

Input Format

The first line contains three integers N,M,QN, M, Q, separated by spaces, where NN is the number of nodes in the template tree, MM is the number of repetitions of the operation in step (2), and QQ is the number of queries.

The next N1N-1 lines each contain two integers fr,tofr, to, representing an edge in the template tree.

Then there are MM lines, each containing two integers x,tox, to, representing one operation that copies the subtree rooted at xx in the template tree and attaches it as a subtree of node toto in the large tree.

Then there are QQ lines, each containing two integers fr,tofr, to, asking for the distance between nodes frfr and toto in the large tree.

N,M,Q100000N, M, Q \leq 100000.

Output Format

Output QQ lines, each containing one integer. The ii-th line is the answer to the ii-th query.

5 2 3
1 4
1 3
4 2
4 5
4 3
3 2
6 9
1 8
5 3
6
3
3

Hint

After two operations, the large tree becomes the shape shown below:

There are 66 edges between nodes 66 and 99, so the distance is 66. Similarly, there are 33 edges between nodes 11 and 88. There are also 33 edges between nodes 55 and 33.

Translated by ChatGPT 5