#K43287. Total Sales Calculation in a Recruitment Hierarchy

    ID: 27276 Type: Default 1000ms 256MiB

Total Sales Calculation in a Recruitment Hierarchy

Total Sales Calculation in a Recruitment Hierarchy

You are given a set of distributors. Each distributor has an individual sale value and may recruit other distributors. The objective is to compute the total sales for each distributor, which is defined as the sales made by the distributor themselves plus the sales of all distributors in their recruitment subtree (i.e. all levels of recruits beneath them).

More formally, if distributor u has sales \( S(u) \) and recruits a set of distributors \( R(u) \), then the total sales for \( u \) is:

[ T(u) = S(u) + \sum_{v \in R(u)} T(v) ]

You are to write a program that reads from stdin the information about the distributors and their recruits, calculates the total sales for each distributor, and prints the result to stdout in the same order as the input.

inputFormat

The input is read from stdin and has the following format:

  1. The first line contains an integer ( n ) representing the number of distributors.
  2. The next ( n ) lines each contain a distributor ID (a string without spaces) and an integer representing the sales made by that distributor.
  3. The following ( n ) lines describe the recruitment list for each distributor. Each of these lines starts with a distributor ID, followed by an integer ( k ) (the number of recruits), and then ( k ) distributor IDs which are the recruits of that distributor.

For example:

5 A 100 B 50 C 40 D 30 E 20 A 2 B C B 2 D E C 0 D 0 E 0

outputFormat

The output should be written to stdout consisting of ( n ) lines. Each line should contain a distributor ID and its corresponding total sales value, separated by a space. The distributors must be printed in the same order as they appeared in the input.

For the sample input above, the output would be:

A 240 B 100 C 40 D 30 E 20## sample

5
A 100
B 50
C 40
D 30
E 20
A 2 B C
B 2 D E
C 0
D 0
E 0
A 240

B 100 C 40 D 30 E 20

</p>