#P17268. [ICPC 2017 Urumqi R] Lowest Common

    ID: 16796 Type: RemoteJudge 1000ms 512MiB Tried: 0 Accepted: 0 Difficulty: 7 Uploaded By: Tags>2017树形 DP最近公共祖先 LCAICPC

[ICPC 2017 Urumqi R] Lowest Common

题目描述

In graph theory the lowest common ancestor (LCA)(LCA) of two nodes vv and ww in a rooted tree TT is the deepest node that has both vv and ww as descendants. Here we define each node to be a descendant of itself. The LCA of two nodes in TT is the shared ancestor of them that is located farthest from the root.

But how about an un-rooted tree?

In this problem you are given an un-rooted tree TT with nn nodes labelled from 11 to nn and several pairs of nodes (vi,wi)(v_i, w_i).

For each node xx of TT, consider the tree rooted by xx which becomes a rooted tree; and calculate the summation ∑iLCA(vi,wi)\sum_{i} LCA(v_i, w_i).

输入格式

The input has several test cases and the first line contains an integer t(1≤t≤28)t (1 \le t \le 28) which is the number of test cases.

For each test case, the first line contains two integers nn and q(1≤n,q≤100000)q (1 \le n, q \le 100000). Each of the following n−1n - 1 lines describes an edge with two integers vv and w(1≤v,w≤n)w (1 \le v, w \le n). Then following qq lines contain qq pairs of nodes (vi,wi)(v_i, w_i) described as above (1≤vi,wi≤n)(1 \le v_i, w_i \le n).

Both of the sum of nn and the sum of qq in input are smaller than 10000001000000.

输出格式

For each test case, output a line with nn integers.

The ii-th one is the value of ∑iLCA(vi,wi)\sum_{i} LCA(v_i, w_i) corresponding to the tree rooted by the ii-th node.

2
4 3
1 2
1 3
1 4
2 3
3 4
2 4
4 1
1 2
2 3
3 4
1 4
3 5 7 9  
1 2 3 4