A deep-space fleet is organized into command chains: every satellite has a unique id, an integer power rating, and a list of the ids of the satellites that report directly to it (its subordinate relays). A satellite's subordinates may themselves have subordinates, forming a hierarchy that can branch arbitrarily deep, and the fleet may contain several independent command chains (a forest, not necessarily a single tree).
Given a queried satellite id, compute the total power: the queried satellite's own power rating plus the power ratings of every satellite reachable by following the chain of command downward (its direct subordinates, their subordinates, and so on, transitively). Satellites outside that chain — including any commander above the queried satellite — must not be counted.
n, the number of satellites.n lines each describe one satellite: id power k s_1 s_2 ... s_k, where id is that satellite's unique id, power is its integer power rating, k is the number of satellites reporting directly to it, followed by the k subordinate ids (omitted if k is 0).queryId, the id of the satellite to query.Print a single integer: the sum of power ratings for queryId and all satellites in its command chain.
queryId is one of the ids 1..n.k values equals n minus the number of root satellites (satellites with no commander).Example 1
Input
4 1 5 2 2 3 2 3 0 3 1 1 4 4 7 0 1
Expected
16
Explanation
Satellite 1 (power 5) has subordinates 2 and 3. Satellite 3 (power 1) has subordinate 4 (power 7). Satellite 2 (power 3) has no subordinates. Querying satellite 1 sums the whole chain: 5 + 3 + 1 + 7 = 16.
Example 2
Input
4 1 5 2 2 3 2 3 0 3 1 1 4 4 7 0 2
Expected
3
Explanation
Same fleet as Example 1, but querying satellite 2, which has no subordinates, so the answer is just its own power rating, 3.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →