Diamond Inheritance (Large)
InterviewTime limit5sMemory limit512 MB
Decide whether any pair of classes in each inheritance DAG has two different inheritance paths between them.
- Level
Medium5 of 10
- Topics
- Graph, Topological sort, Dynamic programming
- Solved
- No attempts yet
Problem
You inspect class diagrams and decide whether they contain a diamond inheritance. The diagram below has four classes , , and . An arrow from to means that class inherits from class .

In this diagram inherits from both and , inherits from , and also inherits from .
An inheritance path from class to class is a sequence of classes in which inherits from , class inherits from for every with , and inherits from . The case counts too: if inherits from directly, the sequence is itself one inheritance path. The example above has two inheritance paths from to , namely and .
A class diagram contains a diamond inheritance if some pair of classes , has at least two different inheritance paths from to . The diagram above is the standard example. Decide whether a given class diagram contains a diamond inheritance.
Input
The first line holds the number of test cases . Then test cases follow, each describing one class diagram.
The first line of a test case holds the number of classes in that diagram. The classes are numbered from to . Of the lines that follow, line starts with the number of classes that class inherits from, , followed by distinct integers between and . Those integers are the numbers of the classes that class inherits from.
The input satisfies the following.
- If there is an inheritance path from to , then there is no inheritance path from to .
- No class inherits from itself.
Limits
Output
For each diagram print one line Case #x: y, where is the test case number starting from , and is Yes if that diagram contains a diamond inheritance and No if it does not.