Fruits in a state

0

0 votes
Data Structures, Disjoint Data Structures, Disjoint Set, Disjoint set, Medium, persistent segment tree
Problem

There are n states in a country. The states are connected to each other by undirected borders and there are total n1 borders between different pairs of states. These borders form a tree. The strength of a border i is ten[i].

Each state grows some fruits. Initially, there are no fruits in any states. The rate at which a fruit is grown in state i is R[i] per unit time. A country that is defined as a tree of connected states is considered rich at an instant if all the states contain at least X fruits.

A company wants to buy these fruits. It buys fruits from the state that contains the lowest production rate in the country and it visits a country only if it is rich. If there are multiple such countries, the company randomly chooses one state and buys from it.

You are required to answer q queries that are represented as follows:

The ith query consists of three space-separated integers ai,bi,ci. They allow you to generate Di, Ti, and Xi as Di=ai^ansi1Ti=bi^ansi1, and Xi=ci^ansi1, where ansi is the answer to the ith query and ans0=0

At t=0, borders whose strength value is greater than Di splits apart and the remaining connected states form separate countries. Your task is to determine the total number of fruits that the company can collect at time Ti.

Note: Each query is independent in nature. 

You are required to answer these queries online because the input of the next query depends on the answer of the previous query.

Input format

  • First line: n and q 
  • n1 lines: Three space-separated integers u v w that represent state u and state v share border whose strength value is w
  • Next line: n space-separated integers where the ith integer is R[i]
  • q lines: Three space-separated integers that are defined in the question

Output format

For each query, print the answer in a new line.

Constraints

1n,q2105

0ten[i],X[i],T[i],D[i]108

0R[i]105

0ai,bi,ci<262

Note: X[i], T[i], and D[i] are generated internally but you must consider these constraints

Time Limit: 2
Memory Limit: 512
Source Limit:
Explanation

first query, since d=0, all cities form individual countries. So min. rate is the same as the max rate for each country since it contains a single city. Cities that can produce at least 7 unit of fruits in 2-time units are city 4 and 5. Answer is (4+5)*2 = 18

second query, d=2, t=3, x=8. d=2 makes 3 countries - first formed by 1--2--3, second consisting of only 4 and third of only 5. Again only 4 and 5 passes the criteria, and the answer is (4+5)*3 = 27

third query, d=0, t=8, x=9. All cities are a separate country. Eligible cities to buy fruit are 2,3,4 and 5. Answer is (2+3+4+5)*8 = 112

Editor Image

?