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...N1. 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 kth 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 4th 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 N1 lines, the ith line describes the ith 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
shishir_hstu:
20170907 20:12:04
easy to solve using LCA with parse tree. also can find KTH parent from parse table. :D 

starbot:
20170907 16:21:53
GOT AC AFTER USING long long.... 

justforpractic:
20170722 23:23:39
when dealing with levels of parents of nodes don't forget to check if parent[node][j] != 1 to avoid Run time error


nitesh_gupta:
20170721 10:21:40
Got segmentation fault in C++(g++4.3.2) but same solution got accepted in C++(gcc 6.3). 

justforpractic:
20170721 02:45:39
Is it sufficient to answer each query in the order of the path from a to b ? 

shubham808:
20170713 09:10:16
there is one blank line between successive test cases _ 

sandeepg97:
20170623 20:53:06
For the KTH query, will O(k) complexity pass? Or something else is required?


sonudoo:
20170525 17:26:38
AC after 4 WA. Feel good. I used RMQ on Level eulerian walk to get LCA and binary search on levels to get kth Ancestor 

cake_is_a_lie:
20170302 00:06:42
This is way easier than QTREE; you don't need HLD, only LCA. You also DO NOT need long long; which you could infer from the input restrictions btw. 

Ashwani Gautam:
20161029 21:07:15
can use hld, use long long int for anything related to summation of edges 
Added by:  ThanhVy Hua 
Date:  20060827 
Time limit:  0.433s 
Source limit:  15000B 
Memory limit:  1536MB 
Cluster:  Cube (Intel G860) 
Languages:  All except: ERL JSRHINO NODEJS PERL6 VB.NET 
Resource:  Special thanks to Ivan Krasilnikov for his alternative solution 