Along a fog-prone coastline, lighthouses fire numbered beacon flashes, and passing ships radio back short acknowledgment records naming the flash they are answering. A relay operator's logbook mixes both kinds of entries together, and because of radio retransmissions the very same acknowledgment sometimes gets logged twice. Given the full logbook, report how many distinct acknowledgments each beacon flash received.
n, the number of logbook entries.n lines contains two integers id parent separated by a space, describing one logbook entry.
parent is -1, the entry records a beacon flash, and id is that flash's identifier.parent, and id is the acknowledgment's own identifier. Every acknowledgment refers directly to a beacon flash — never to another acknowledgment.id may appear on more than one line (an accidental retransmission); every line carrying a given id describes the exact same logbook entry and must be counted only once.Print one line per distinct beacon flash, in ascending order of its identifier, as two integers separated by a space: the flash's identifier followed by the number of distinct acknowledgments it received (0 if none).
1 <= n <= 2000001 <= id <= 10^9 for every entryparent is either -1 or an id that appears somewhere in the log as a beacon flash (i.e. with parent = -1)parent = -1 (there is always at least one beacon flash).Example 1
Input
5 101 -1 201 101 202 101 201 101 303 -1
Expected
101 2 303 0
Explanation
Entries 101 and 303 have parent -1, so they are beacon flashes. Entries 201 and 202 both name parent 101; entry 201 appears twice (a retransmission) but counts once, so flash 101 has 2 distinct acknowledgments (201 and 202). Flash 303 has no acknowledgment entries at all, so its count is 0. Sorted ascending by id: 101 first, then 303.
Example 2
Input
6 10 -1 50 -1 11 10 12 10 51 50 11 10
Expected
10 2 50 1
Explanation
Flashes are 10 and 50. Acknowledgments 11 and 12 both name parent 10 (11 is logged twice but counts once), giving flash 10 a count of 2. Acknowledgment 51 names parent 50, giving flash 50 a count of 1. Sorted ascending by id: 10 then 50.
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 →