For each employee, sum t_j over all descendants j whose rank r_j is lower than the employee's rank.
Medium7TreeDFSSegment treePrefix sumNo attempts yetTime limit2sMemory limit512 MB
In the engineering division of a company, every employee except the director reports to one manager, and every employee reports to the director directly or through a chain of managers. Maria runs the performance review system of the division. Letting managers assess their direct reports did not work well, so Maria built a new system that gives each employee a technical rank.
Under the new system an employee reviews only the subordinates whose technical rank is lower. The subordinates of employee i are the employees who report to i directly and the employees who report to i through a chain of managers. Employee j writes a summary of recent work and estimates tj, the time one review of that summary takes. Every superior of j whose technical rank is higher than rj spends tj writing the review of j. A superior with the same technical rank writes no review.
Maria wants to know the load this creates. Given the structure of the division, compute the total time each employee spends writing reviews.
The first line contains one integer E, the number of employees, who are numbered 1 to E. The next E lines describe employee 1 up to employee E in that order. Line i contains three space separated integers mi, ri, ti: the manager, the technical rank, and the expected time of one review of employee i. The director has no manager and is given as mi=−1. Every other employee has mi between 1 and E.
Print E lines. Line i holds the total time employee i spends writing reviews.