Klingon Warfare

No attempts yetTime limit5sMemory limit128 MB

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 TT (1T501 \le T \le 50), the number of test cases.

Each test case begins with a line with two integers MM and NN (1M,N100001 \le M, N \le 10000), the sizes of the two clans. The next MM lines describe the first clan. Line ii contains an uppercase letter fif_i and an integer sis_i, the fighting style and the superior of warrior ii. Warriors are numbered from 0, warrior 0 is always the clan leader and therefore has s0=1s_0 = -1, and every warrior with i1i \ge 1 satisfies 0si<i0 \le s_i < i. Warriors are listed from eldest to youngest. The next NN lines describe the second clan in the same format, giving the fighting style fjf_j and the superior sjs_j of warrior jj.

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.