Relative Relatives

Interview

Time limit1sMemory limit128 MB

Summary
Given Ted's age of 100 and each descendant's father name plus the father's age at the child's birth, compute every descendant's age and list them oldest first, ties broken by name.
Level

Medium4 of 10

Topics
Tree, DFS, Sorting, Hash map
Solved
No attempts yet

Problem

Today is Ted's 100th birthday. A few weeks ago the family chose you to track down all of Ted's descendants and throw a surprise party. To make the job easier, you decide to build a single list of everyone descended from Ted, ordered from oldest to youngest. Descendants who are the same age are listed in dictionary order.

The only records you have are birth certificates. Strangely, none of them are dated. Each certificate lists only three things: the father's name, the child's name, and the father's exact age (in whole years) at the moment the child was born.

Because every descendant of Ted shares Ted's birthday, the age gap between any two people is always a whole number of years. Ted turns 100 today, so his age is 100.

Input

The first line contains a single integer nn, the number of data sets. Each data set is formatted as follows.

A data set has two parts:

  1. Descendant count — a line with a single integer XX (0<X<1000 < X < 100), the number of Ted's descendants.
  2. Birth certificate list — XX lines, one certificate per line, each in the format FNAME CNAME FAGE, where:
    • FNAME is the father's name.
    • CNAME is the child's name.
    • FAGE is the father's whole-year age on the day CNAME was born.

Notes:

  • Names are unique identifiers and contain no embedded whitespace.
  • Every descendant of Ted shares Ted's birthday, so the age difference between any two of them is a whole number of years.
  • The certificates are a complete collection: there is exactly one certificate for every descendant of Ted.

Output

For each data set, print X+1X + 1 lines. The first line is DATASET Y, where YY is 11 for the first data set, 22 for the second, and so on. The next XX lines are the age-prioritized list of Ted's descendants, one per line in the format NAME AGE, ordered from oldest to youngest. Descendants of the same age are listed in dictionary order.

Examples1

  1. Example 1

    Input
    2
    1
    Ted Bill 25
    4
    Ray James 40
    James Beelzebub 17
    Ray Mark 75
    Ted Ray 20
    
    Expected output
    DATASET 1
    Bill 75
    DATASET 2
    Ray 80
    James 40
    Beelzebub 23
    Mark 5