Klingon Warfare
Time limit5sMemory limit128 MB
Pick one subclan from each ordered clan tree so the pair matches in style, child count and sibling order with the largest size.
- Level
Medium6 of 10
- Topics
- Tree, Hash map, Dynamic programming
- Solved
- No attempts yet
Problem
War has broken out between two Klingon clans. A Klingon war is never ordinary. It must be honorable and glorious. Honor requires that the two sides be exactly matched. Glory requires that as many warriors take part as possible.
Each clan follows a strict hierarchy. One leader commands the whole clan, and that leader may have zero or more direct subordinates, listed from eldest to youngest. Each subordinate may in turn have zero or more direct subordinates of his or her own, also listed from eldest to youngest, and so on down the hierarchy. By tradition every warrior is younger than his or her superior. Each warrior also specializes in exactly one fighting style.
The subclan commanded by a warrior consists of that warrior together with every direct and indirect report: subordinates, subordinates of subordinates, and so on. Two subclans match exactly when both of the following hold. First, the two leaders have the same fighting style and the same number of direct subordinates. Second, when the direct subordinates of each leader are listed from eldest to youngest, the subclans commanded by the first subordinates match exactly, the subclans commanded by the second subordinates match exactly, and the same holds at every remaining position.
Each clan sends one warrior and that warrior's entire subclan into the war. The two chosen subclans must match exactly and must be as large as possible. How many warriors fight for each clan?
Input
The first line contains one integer (), the number of test cases.
Each test case begins with a line with two integers and (), the sizes of the two clans. The next lines describe the first clan. Line contains an uppercase letter and an integer , the fighting style and the superior of warrior . Warriors are numbered from 0, warrior 0 is always the clan leader and therefore has , and every warrior with satisfies . Warriors are listed from eldest to youngest. The next lines describe the second clan in the same format, giving the fighting style and the superior of warrior .
Output
For each test case, print one line with the largest number of warriors that each clan may send to fight. If no pair of subclans matches exactly, print 0.