Finding Your Roots
InterviewTime limit1sMemory limit1024 MB
For each data set, count how many lions lie on the parent chain from lion L upward, including L, until the chain reaches an unknown parent.
- Level
Easy2 of 10
- Topics
- Implementation, Linked list
- Solved
- No attempts yet
Problem
P-22's father was P-1, the first mountain lion tagged in the Santa Monica Mountains. P-22's mother is unknown. Unfortunately, we do not know anything about P-1's parents, so we can only trace back P-22's ancestry two generations (himself and his father). In some other cases, one can trace back ancestry quite a bit further, and you are supposed to find out just how far.
To keep things simple (and avoid exponential growth), each mountain lion is given only one parent, or none when no information is available. Return the total number of generations in the ancestry of a specific mountain lion that can be traced back.
Input
The first line contains the number of data sets . This is followed by data sets.
The first line of a data set contains two integers . is the total number of mountain lions in the database, and is the mountain lion whose ancestry you are interested in.
The next line contains integers , where is the parent of mountain lion . A means the parent of lion is unknown. Because these are parent relationships, the input never contains cycles.
Output
For each data set, print Data Set x: on its own line, where is the data set number. Then print the number of generations of the ancestry of that are in the database, including himself or herself.
Print a blank line after each data set.