QTREE2 - Query on a tree II


You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2, 3...N-1. Each edge has an integer value assigned to it, representing its length.

We will ask you to perfrom some instructions of the following form:

  • DIST a b : ask for the distance between node a and node b
    or
  • KTH a b k : ask for the k-th node on the path from node a to node b

Example:
N = 6
1 2 1 // edge connects node 1 and node 2 has cost 1
2 4 1
2 5 2
1 3 1
3 6 2

Path from node 4 to node 6 is 4 -> 2 -> 1 -> 3 -> 6
DIST 4 6 : answer is 5 (1 + 1 + 1 + 2 = 5)
KTH 4 6 4 : answer is 3 (the 4-th node on the path from node 4 to node 6 is 3)

Input

The first line of input contains an integer t, the number of test cases (t <= 25). t test cases follow.

For each test case:

  • In the first line there is an integer N (N <= 10000)
  • In the next N-1 lines, the i-th line describes the i-th edge: a line with three integers a b c denotes an edge between a, b of cost c (c <= 100000)
  • The next lines contain instructions "DIST a b" or "KTH a b k"
  • The end of each test case is signified by the string "DONE".

There is one blank line between successive tests.

Output

For each "DIST" or "KTH" operation, write one integer representing its result.

Print one blank line after each test.

Example

Input:
1

6
1 2 1
2 4 1
2 5 2
1 3 1
3 6 2
DIST 4 6
KTH 4 6 4
DONE

Output:
5
3

hide comments
Ashwani Gautam: 2016-10-29 21:07:15

can use hld, use long long int for anything related to summation of edges

prudvinit: 2016-09-22 15:01:07

Last edit: 2016-09-22 15:02:31
nk17kumar: 2016-08-28 21:03:27

easy . sparse Matrix approach for LCA calculation.

nonushikhar: 2016-07-26 19:51:48

easy ;) confidence booster

moss3011: 2016-05-15 09:32:36

getting tle may be bcoz of method of finding ancestors ...plz help

sigma_poet225: 2016-04-03 03:22:29

Get Wa and Don't know why.

Abhinandan Agarwal: 2016-03-26 14:13:56

@chandan Mittal- No, I checked it.

Last edit: 2016-03-26 14:35:26
latte0119: 2015-10-22 11:03:20

I was using doubling algorithm to get lca.
This problem is very easy.

paimon: 2015-06-26 17:59:44

beware test cases "DIST a a" and "KTH a a 1"

Last edit: 2015-06-26 18:00:27
Luis Manuel D�az Bar�n: 2014-10-12 21:27:20

I was using a LCA algorithm with NlogN preprocess and O(1) query and received rte, I changed it to NlogN preprocess and logN query... now I received TLE, wdf is wrong with this problem? Finding the Kth ancestor ran in O(N) for the worst case. Help Please. My Mail:
luismo@princesa.pri.sld.cu

Last edit: 2014-10-12 21:28:39

Added by:Thanh-Vy Hua
Date:2006-08-27
Time limit:0.433s
Source limit:15000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ERL JS NODEJS PERL 6 VB.net
Resource:Special thanks to Ivan Krasilnikov for his alternative solution