Shuffled Tree - ReimuOJ: Reimu Online Judge

Shuffled Tree

Time limit: 2000 ms
Memory limit: 512 MB
Given a tree T with n vertices and n−1 weighted edges, initially, vertex i is assigned color i for 1≤i≤n. Since Marisa is dissatisfied with the structure of the tree T, she decides to shuffle the tree T to obtain a new tree T′, where vertex i will have the color pi (1≤i≤n), and p1,p2,…,pn is a permutation of 1,2,…,n. After shuffling the tree T, Marisa provides q queries. Each query i consists of ui,vi,xi. For the simple path from ui to vi in tree T, let the set of distinct colors on this path be s1,s2,…,sk. Compute the total distance from xi to every vertex with color sj in tree T′, for all 1≤j≤k. ### Input - The first line contains two positive integers n and q. - The second line contains n positive integers p1,p2,…,pn. - The next n−1 lines, the i-th line contains three positive integers ui,vi,wi, describing an edge of the tree with weight wi. - The next q lines, the i-th line contains three positive integers ui,vi,xi. ### Output - Print q lines, each containing the answer to the corresponding query. ### Constraints - 1≤n,q≤105. - wi≤103. ### Example Input 5253214121231242152341515 Output 57
Topic
Tree
Data structure
Rating 2400
Source MarisaOJ Original
Solution (0) Solution