#abc298h. Ex - Sum of Min of Length

Ex - Sum of Min of Length

Score : 600600 points

问题描述

你被给定一棵包含 NN 个顶点的树。顶点按从 11NN 编号,第 ii 条边连接顶点 AiA_i 和顶点 BiB_i

d(x,y)d(x,y) 表示在该树中顶点 xx 和顶点 yy 之间的距离。这里,顶点 xx 和顶点 yy 之间的距离是指从顶点 xx 到顶点 yy 的最短路径上的边数。

按照顺序回答 QQ 个查询。第 ii 个查询如下:

  • 给定整数 LiL_iRiR_i,求 $\displaystyle\sum_{j = 1}^{N} \min(d(j, L_i), d(j, R_i))$。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

You are given a tree with NN vertices. The vertices are numbered 11 to NN, and the ii-th edge connects vertex AiA_i and vertex BiB_i.

Let d(x,y)d(x,y) denote the distance between vertex xx and yy in this tree. Here, the distance between vertex xx and yy is the number of edges on the shortest path from vertex xx to yy.

Answer QQ queries in order. The ii-th query is as follows.

  • You are given integers LiL_i and RiR_i. Find $\displaystyle\sum_{j = 1}^{N} \min(d(j, L_i), d(j, R_i))$.

Constraints

  • 1N,Q2×1051 \leq N, Q \leq 2 \times 10^5
  • 1Ai,Bi,Li,RiN1 \leq A_i, B_i, L_i, R_i \leq N
  • The given graph is a tree.
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

NN

A1A_1 B1B_1

\vdots

AN1A_{N-1} BN1B_{N-1}

QQ

L1L_1 R1R_1

\vdots

LQL_Q RQR_Q

Output

Print QQ lines. The ii-th line should contain the answer to the ii-th query.

Sample Input 1

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

Sample Output 1

4
6
3

Let us explain the first query.
Since d(1,4)=2d(1, 4) = 2 and d(1,1)=0d(1, 1) = 0, we have min(d(1,4),d(1,1))=0\min(d(1, 4), d(1, 1)) = 0.
Since d(2,4)=2d(2, 4) = 2 and d(2,1)=2d(2, 1) = 2, we have min(d(2,4),d(2,1))=2\min(d(2, 4), d(2, 1)) = 2.
Since d(3,4)=1d(3, 4) = 1 and d(3,1)=3d(3, 1) = 3, we have min(d(3,4),d(3,1))=1\min(d(3, 4), d(3, 1)) = 1.
Since d(4,4)=0d(4, 4) = 0 and d(4,1)=2d(4, 1) = 2, we have min(d(4,4),d(4,1))=0\min(d(4, 4), d(4, 1)) = 0.
Since d(5,4)=1d(5, 4) = 1 and d(5,1)=1d(5, 1) = 1, we have min(d(5,4),d(5,1))=1\min(d(5, 4), d(5, 1)) = 1.
0+2+1+0+1=40 + 2 + 1 + 0 + 1 = 4, so you should print 44.

Sample Input 2

8
4 2
4 1
5 6
6 1
7 6
8 1
3 7
7
8 4
4 4
7 2
4 4
5 3
4 4
6 1

Sample Output 2

14
16
10
16
14
16
8

update @ 2024/3/10 12:23:30

}