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 perform 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
riaj_123: 2023-10-02 16:48:05

Very easy just LCA

baodepzai: 2023-09-14 10:16:47

easy one

metalavocado99: 2023-05-23 10:59:23

DANG , this sounds hard as hell

ahmed_bahu: 2022-08-18 07:28:51

what is the root of the tree ?

outcast0216: 2021-11-08 14:37:28

How can I get the data of this problem ?
I have got so many WA , but still unable to find my mistake :-(

ppap_1264589: 2021-09-15 19:04:07

If you use LCA for this problem, remember to check if 'a' and 'b' in a same branch and 'a' is closer to the root than 'b'
This case cost me some WA .-.

mhasan01: 2020-07-10 00:46:46

Nice, used HLD, although binary lifting would probably be better

tarungupta: 2020-06-21 06:43:11

A must do question to learn LCA.

Last edit: 2020-06-21 06:43:28
saurabhshadow: 2020-05-13 19:13:04

Updated: AC
I am using binary lifting approach but getting the wrong answer.

Last edit: 2020-05-14 09:42:54
black_shroud: 2020-05-09 15:14:03

just check your preprocessing fn if you are getting segmentation fault


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