Given M rankings of N universities, find the longest sequence where each earlier university beats the next in every ranking.
Medium6Dynamic programmingSortingPrefix sumNo attempts yetTime limit8sMemory limit512 MBA rating agency publishes one ranking list per department. Every university in the survey runs the same M departments, and each department list places all N universities in a strict order from best to worst.
Because there are many lists, two universities often cannot be ordered against each other. The agency therefore uses a relation it calls absolutely better: university X is absolutely better than university Y when X comes before Y in every one of the M department rankings.
Take three universities X, Y, Z and three departments CS, EE, FLS with these rankings:
X comes before Y in all three lists, so X is absolutely better than Y. X and Z cannot be ordered: X leads in CS, Z leads in FLS.
Find universities U1,…,Uk such that Ui is absolutely better than Uj for every i<j. Report the largest possible k. Universities are given as numbers.
The first line holds one integer C, the number of test cases (1≤C≤10).
Each test case begins with a line holding two integers N and M (1≤N,M≤400), the number of universities and the number of departments. M lines follow. The k-th of them holds N integers, a permutation of 1 through N, listing the universities of the k-th department's ranking from best to worst. If university U appears before university V on that line, the k-th department of U is better than the k-th department of V.
Print C lines, one per test case in the order given, each holding the largest possible k. Print no extra spaces.