OCC '19 G6 - Monkeys in a Tree

View as PDF

Submit solution

Points: 30 (partial)
Time limit: 2.75s
Memory limit: 512M

Problem types

In DMOJ forest, there is a tree with N nodes, conveniently numbered from 1 to N, connected by N1 weighted edges. The ith edge connects nodes ui and vi with distance wi. On each node, a monkey lives there. The monkey at node i has a ranking ri. Multiple monkeys may have the same ranking.

Monkey king plans to host a banana eating competition. He picks up a node X as the location and invites monkeys whose rankings are within [L,R] (i.e. LriR) to attend this event. Monkey king wants to figure out the sum of distances for all invited monkeys travelling to X. Since monkey king hasn't found out the best location, he will ask you Q queries. In the ith query, he will give you Xi, Li and Ri. You need to tell him the sum of distances for monkeys with rankings in [Li,Ri] travelling to Xi. Because monkey king is quite impatient, you must answer his queries online.

Constraints

For all subtasks:

1N150000

1Q200000

1M109

Subtask Points Additional constraints
1 19 N3000, Q300, M109
2 21 N105, Q105, M20
3 23 N105, Q105, M109
4 37 No additional constraints.

Input Specification

The first line contains three integers, N, Q, and M (1N150000, 1Q200000, 1M109), where N is the number of nodes in the tree, Q is the number of queries, and M is used to decode each query.

The second line contains N integers, ri, (0ri<M), the ranking of the ith monkey.

Each of the following N1 lines contains three integers, ui, vi and wi, (1ui,viN, 1wi1000), an edge between nodes ui and vi with length wi.

Q lines of input follow. The ith line contains three integers, Xi, li and ri, where li and ri are the encoded ranking interval. You can get the actual Li and Ri by calculating Li=min((li+lastans)%M,(ri+lastans)%M) and Ri=max((li+lastans)%M,(ri+lastans)%M), where lastans is the answer for the previous query, and specially lastans=0 for the first query.

Output Specification

Print Q lines. The ith line contains an integer, the sum of distances for the ith query.

Sample Input

Copy
10 5 10
0 0 7 2 1 4 7 7 7 9
1 2 5
2 3 3
1 4 4
2 5 6
4 6 5
3 7 2
1 8 7
6 9 3
7 10 4
8 9 8
2 8 0
9 3 1
8 0 8
4 2 7

Sample Output

Copy
21
75
61
117
68

Comments

There are no comments at the moment.