Fruits in a state

0

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

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

Each state grows some fruits. Initially, there are no fruits in any states. The rate at which a fruit is grown in state  is 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 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 queries that are represented as follows:

The  query consists of three space-separated integers . They allow you to generate  as , and , where  is the answer to the  query and 

At , borders whose strength value is greater than 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 .

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: and  
  •  lines: Three space-separated integers  that represent state and state share border whose strength value is
  • Next line: n space-separated integers where the  integer is
  • 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

Note: 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

?