Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?
The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.
Output
Print the length of the longest common subsequence.
Examples
Input
4 3
1 4 2 3
4 1 2 3
1 2 4 3
Output
3
Note
The answer for the first test sample is subsequence [1, 2, 3].
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given n up to 1000, k up to 5. We have k permutations of numbers 1..n. Need the length of the longest common subsequence (LCS) among these k permutations.
This is a classic problem: LCS of multiple sequences is NP-hard in general, but here the sequences are permutations. For two permutations, LCS reduces to longest increasing subsequence (LIS) after mapping: given two permutations, the LCS length equals the length of the longest increasing subsequence in the positions array of the first permutation in the second permutation? Actually, standard: For two permutations of n, LCS is equivalent to longest common subsequence, which is same as longest increasing subsequence of the indices of the second permutation when numbers are mapped to positions in the first permutation. Let me recall: For two permutations π1 and π2 of set {1..n}, define an array a where a[i] = position of element i in π1? Actually typical: Given permutations p and q, the LCS length equals the length of the longest increasing subsequence of the sequence formed by the positions in q of the elements as they appear in p. More precisely: Let pos2[x] = index of x in q. Then consider the sequence S = (pos2[p[1]], pos2[p[2]], ..., pos2[p[n]]). Then the LCS of p and q is the length of the LIS of S. Because a common subsequence corresponds to an increasing subsequence in the positions of both sequences? Indeed, common subsequence corresponds to a subsequence where the order is preserved. If we map p to positions in q, then a common subsequence corresponds to a set of indices in p that are increasing in p (trivial) and also their images in q are increasing, because in the subsequence we take, the order in both must be same. So the condition is that the positions in q are increasing. So the longest common subsequence length is the length of the longest subsequence of p such that the positions in q are increasing, which is exactly the LIS of the sequence of pos2[p[i]]. That works for two permutations.
Now for k permutations (k up to 5), we need the longest sequence that is a subsequence of all permutations. Since each is a permutation of 1..n, a common subsequence corresponds to a set of numbers that appear in the same relative order in each permutation. That means we need to choose a subset of numbers such that for every pair of numbers in the chosen set, their relative order is consistent across all permutations. In other words, if we define for each permutation a total order (the order of numbers), then a common subsequence corresponds to a chain in the intersection of these orders. More precisely, define for each permutation π_m (m=1..k), we have an order: x <_m y if x appears before y in π_m. Then a set S is a common subsequence if it is totally ordered consistently in each permutation, i.e., there is a linear order that respects all individual orders. But we are free to choose any ordering of S that is consistent? Actually if we take the numbers in S and consider the order they appear in any permutation, they must be the same (since we require a common subsequence; the subsequence itself is some ordering of the numbers, but to be a subsequence of each permutation, that ordering must appear as a subsequence in each, meaning that the numbers appear in that order in each permutation). So the actual order of the subsequence is the same across all permutations. So there is a linear ordering of S (the order in which they appear in the common subsequence) such that for each permutation, that ordering is consistent with the permutation's order. Equivalently, we need to find the longest sequence (i1, i2, ..., iL) such that for each permutation m, pos_m[i1] < pos_m[i2] < ... < pos_m[iL]. Where pos_m[x] is the position of x in permutation m.
So the problem reduces to: given k permutations of n, we need to find the longest sequence of distinct numbers (from 1..n) that is increasing in all k position arrays.
This is reminiscent of finding the longest chain in a partially ordered set (poset) where the partial order is defined by: x < y if for all m, pos_m[x] < pos_m[y]. So we need the size of the longest chain (i.e., maximum number of mutually comparable elements under this partial order). Since the poset is defined as the intersection of k total orders, it is a partial order known as a permutation poset. The size of the longest chain can be found by dynamic programming: for each element i, compute dp[i] = 1 + max{dp[j] : j < i in all permutations}. That is, we need to consider all j such that in every permutation, pos_m[j] < pos_m[i]. Then dp[i] is the length of longest chain ending at i. The answer is max dp[i].
The naive O(n^2 * k) is possible: for each i, iterate over all j, check k conditions (pos_m[j] < pos_m[i]), O(k) each, total O(k * n^2). With n <= 1000, n^2 = 1e6, k <= 5, so 5e6 operations, which is fine. However we need to be careful: O(n^2 * k) = 5e6, well within limits. Actually n=1000, n^2=1e6, times k=5 => 5e6. That's fine.
But maybe we can do better? Not needed.
Edge: there might be more efficient ways using bitsets or topological order, but we'll just implement DP.
We need to compute pos for each permutation: an array of size n+1 (1-indexed). For each permutation input (list of n numbers), fill pos[number] = index (1-indexed).
Then we can compute dp: For i from 1 to n, dp[i] = 1. Then for each i, we iterate over all j from 1 to n, if j != i and for all m, pos_m[j] < pos_m[i], then dp[i] = max(dp[i], dp[j] + 1). Since we need an ordering to ensure DP works: We need to process i in an order that respects the partial order to avoid cycles. But if we compute dp in any order and do this full check, it's still correct because we might compute dp[i] before dp[j] but dp[j] might not be computed yet. However we can simply compute dp[i] after we have computed dp for all possible predecessors? Since we are doing dp[i] = 1 + max over all j that satisfy condition, but if dp[j] is not yet computed when we process i, we may underestimate. So we need to ensure we process in an order that respects the partial order. However the partial order is a DAG (since if x<y and y<x can't happen due to strict inequalities). But we don't have a linear extension readily. We can sort by one of the permutations (say the first one) because in the first permutation, if pos1[x] < pos1[y], then x could be a predecessor of y, but not necessarily if other permutations violate. However we can still compute dp by iterating i in increasing order of pos1 (i.e., in the order of the first permutation). Because if j is a predecessor of i, then necessarily pos1[j] < pos1[i] (since in all permutations, must hold for the first as well). So by processing i in increasing order of pos1, any predecessor j will have pos1[j] < pos1[i] and thus will be processed before i if we iterate in that order. That ensures dp[j] is computed before dp[i]. So we can create an order array order[1..n] = the numbers in the order they appear in permutation1. Or we can just iterate through indices of permutation1: for idx from 1 to n: let i = perm1[idx]; then compute dp[i] by checking all j (maybe all numbers) but it's safe because any predecessor j will have pos1[j] < pos1[i] so j appears earlier in perm1 order and thus dp[j] already computed. So DP works.
Alternatively we can just sort the numbers by pos1 ascending and then do DP.
Thus algorithm:
Input n, k.
For each m = 1..k: read permutation array perm_m[1..n] (1-indexed). Build pos_m[1..n] where pos_m[x] = index of x in perm_m.
Create order list = numbers in the order they appear in perm1: that is, order[1..n] = perm1[1..n].
Initialize dp[1..n] = 1.
For idx from 1 to n:
i = order[idx];
for j from 1 to n:
if j == i: continue
// check if j is predecessor: for all m, pos_m[j] < pos_m[i]
bool ok = true;
for m=1..k:
if pos_m[j] >= pos_m[i]: {ok=false; break;}
if ok:
dp[i] = max(dp[i], dp[j] + 1);
answer = max(dp[1..n]).
Complexity: O(k * n^2). n=1000, k<=5 => fine.
But careful: The inner j loop goes over all numbers (1..n) each time, so total O(n^2 * k). That's okay.
We could reduce constant by preprocessing adjacency: But not needed.
We also need to consider that the LCS can be empty? dp=1 for singletons, answer at least 1, but n>=1. Possibly answer could be 0 if n=0? But n>=1, so answer >=1.
Now order by perm1: [1,4,2,3].
Compute dp[1]=1.
i=4: check j=1: pos1[1]=1<2 ok; pos2[1]=2<1? No, pos2[4]=1, pos2[1]=2, so 2 < 1 false => not predecessor.
j=2: pos1[2]=3<2? false.
j=3: pos1[3]=4<2 false.
so dp[4]=1.
i=2: check j=1: pos1[1]=1<3 ok; pos2[1]=2<3 ok; pos3[1]=1<2 ok => dp[2]=dp[1]+1=2.
j=4: pos1[4]=2<3 ok; pos2[4]=1<3 ok; pos3[4]=3<2? false -> no.
j=3: pos1[3]=4<3 false.
dp[2]=2.
i=3: check j=1: pos1[1]=1<4 ok; pos2[1]=2<4 ok; pos3[1]=1<4 ok -> candidate dp[1]+1=2; dp[3] initially 1 -> becomes 2.
j=2: pos1[2]=3<4 ok; pos2[2]=3<4 ok; pos3[2]=2<4 ok -> dp[2]+1=3 -> dp[3]=3.
j=4: pos1[4]=2<4 ok; pos2[4]=1<4 ok; pos3[4]=3<4 ok -> dp[4]+1=2 -> less.
dp[3]=3.
max=3. answer=3. correct.
Thus solution works.
But careful: In DP, we need to consider only j that have been processed. Since we process in perm1 order, any j with pos1[j] < pos1[i] will be processed earlier. But it is possible that j is a predecessor (pos_m[j] < pos_m[i] for all m) but pos1[j] might be greater than pos1[i]? That can't happen because if j is a predecessor, it must satisfy pos1[j] < pos1[i] (since m=1 included). So indeed any predecessor j appears earlier in perm1 order, so dp[j] already computed. So fine.
One nuance: The DP as described will consider all j, but some j with pos1[j] > pos1[i] would not be predecessors (since they'd fail pos1 condition) anyway. So it's safe.
Time complexity: For each i (1000), j loop 1000 => 1e6, inside checking k conditions (max 5) => up to 5e6 operations. That's very fast.
But wait: we have to read permutations and compute pos. That's fine.
Memory: O(n*k) = small.
Thus straightforward solution.
But there is potential to speed up using bitsets or something, but not necessary.
Edge Cases:
n=1: then answer is 1.
k=2: DP will find LIS equivalent. But still fine.
If all permutations are identical, then answer n.
If permutations are reversed, answer 1 because only singletons can be common? Actually if they are all reversed order, common subsequence can be any decreasing sequence? But since each is reverse order, any increasing sequence in one would be decreasing in the other. For two reversed permutations, LCS length = 1 (since only singletons). For more than 2, might be something similar. But DP will handle.
Now confirm constraints: n up to 1000, k up to 5. Works.
Thus solution is O(k * n^2) DP.
Implementation details:
We'll store pos as a vector<vector> pos(k, vector(n+1)) (0-indexed for permutations). Or array of size k+1 each an array of size n+1.
We'll read each permutation line into vector perm(k? Actually each is length n). For m from 0 to k-1: read n ints; for idx from 0 to n-1: number = perm_m[idx]; pos[m][number] = idx (or idx+1 for 1-indexed positions). We'll likely use 0-indexed positions for easier checks? Actually we need comparisons pos_m[j] < pos_m[i]; using 0-indexed works as well: index from 0 to n-1. Then we can treat positions as integers. It doesn't matter. Use 0-index for simplicity.
Then order = perm[0] (the first permutation). Actually careful: The first permutation input is a separate line; we can store perm0. We also need pos for the first permutation, which we compute. So order = perm0.
DP array dp of size n+1, but we can index by number (1..n). Initialize dp[i]=1.
Iterate idx from 0 to n-1: i = order[idx];
for j from 1 to n:
if j == i continue;
bool ok = true;
for m=0..k-1:
if pos[m][j] >= pos[m][i] then ok=false; break;
if ok: dp[i] = max(dp[i], dp[j] + 1);
After loop, answer = max over i dp[i].
Complexities: O(k*n^2). Works.
Potential improvement: Instead of iterating over all j each time, we could precompute something, but not needed.
Now, but we must be careful: The DP as written runs for each i, and inside j loop, we check all j. That includes j that have not been processed yet (i.e., with pos1[j] > pos1[i]), but they cannot be predecessors as argued, so the condition will fail at m=0 because pos0[j] >= pos0[i] (since pos0 is pos for first permutation). However it might be that j with pos0[j] > pos0[i] still satisfies pos0[j] < pos0[i]? No, that would be false. So they will be rejected quickly; we still have to check condition, which includes checking pos0[j] >= pos0[i] which will be true and break, so it's cheap. So overall still O(n^2 * k) worst-case but with early exit? We check all j, each j checks up to k comparisons; for many j the first comparison fails. This is still fine.
But perhaps we can reduce constant by iterating only over candidates that appear earlier in the first permutation: Since a predecessor must have pos0[j] < pos0[i], we can loop over j from order[0..idx-1] only. That reduces inner loop to O(i) on average, halving the operations. Actually total operations become about n^2/2 * k, still similar magnitude but better constant. We can implement that: For each idx, i = order[idx]; Then for prev_idx from 0 to idx-1: j = order[prev_idx]; then check if for all m=1..k-1 (since m=0 condition already satisfied by order) pos[m][j] < pos[m][i]. If true, update dp[i]. That reduces number of j considered and eliminates need to check m=0. Complexity still O(k * n^2/2). This is better.
Let's adopt that.
Thus algorithm with improved inner loop:
Compute order = perm1 (the first permutation) as list.
For each idx from 0 to n-1:
i = order[idx];
dp[i] = 1;
for prev_idx from 0 to idx-1:
j = order[prev_idx];
bool ok = true;
for m=1..k-1: // m=0 automatically true since j appears earlier in perm1
if pos[m][j] >= pos[m][i]:
ok = false; break;
if ok:
dp[i] = max(dp[i], dp[j] + 1);
Answer = max(dp[i]).
Actually we also need to consider m=0? Since we rely on order from perm1, j's pos0 is less than i's pos0 automatically, because prev_idx < idx. So we can skip checking m=0. That is correct as long as we are using the exact same permutation as the one used for ordering. But what if there is a situation where j appears earlier in perm1, but due to indexing we have pos0[j] < pos0[i] obviously. So it's valid.
Thus we only need to check the other k-1 permutations.
Now, is it possible that j appears earlier in perm1 but still is not a predecessor because some other permutation violates order? Yes, that's why we need to check others.
Thus the DP is correct.
Complexity: O(n^2 * (k-1)) ~ up to 4 * 1e6 = 4e6, even better.
One more nuance: The DP uses dp[j] values that have already been computed because we process in order of perm1, and j from earlier indices are processed. So dp[j] is known.
Now note: It is possible that two different numbers have the same position? Not in permutations because each number appears exactly once, so positions are unique per permutation. So inequalities are strict.
Now we must consider that the partial order may have many comparabilities? The DP approach yields the longest chain.
Thus solution is straightforward.
However, I recall that for k=5, n=1000, O(4 * 1e6) = 4 million checks, each check up to 4 comparisons (k-1). That's 16 million comparisons, trivial.
Thus implementation in C++ easy.
But note: We need to be careful about reading input fast, but with n=1000 it's fine.
Now provide a final answer.
One more thing: The problem statement says "You can read about longest common subsequence there: ..." So it's standard LCS.
Thus final solution code.
Edge: Could there be multiple test cases? Not specified. Only one case.
Thus final answer.
But I'll think about correctness proof: The DP effectively computes the size of the longest chain in the poset defined by x < y iff for all m, pos_m[x] < pos_m[y]. This chain corresponds to a common subsequence by taking the numbers in increasing order of their positions, and any common subsequence corresponds to a chain. So maximum chain length equals LCS length. So correct.
Now confirm the time complexity: O(k * n^2) worst-case but optimized to O((k-1)*n^2) using order of first permutation.
Now, I'll write the code accordingly.
Pseudo:
int n, k;
cin >> n >> k;
vector<vector> pos(k, vector(n+1));
vector first_perm(n);
for (int m = 0; m < k; ++m) {
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (m == 0) first_perm[i] = x;
pos[m][x] = i; // 0-indexed position
}
}
vector dp(n+1, 1);
int ans = 1;
for (int idx = 0; idx < n; ++idx) {
int i = first_perm[idx];
dp[i] = 1; // could be already 1 but set to 1 (though dp[i] may already be 1)
for (int jdx = 0; jdx < idx; ++jdx) {
int j = first_perm[jdx];
bool good = true;
for (int m = 1; m < k; ++m) {
if (pos[m][j] >= pos[m][i]) {
good = false;
break;
}
}
if (good) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
ans = max(ans, dp[i]);
}
cout << ans << endl;
But there is one nuance: dp[i] might have been set earlier? Actually we only set dp[i] at this iteration, but we initially set dp[1..n] = 1. Then we update dp[i] inside loop. That works.
Alternatively, we could not initialize dp with 1, but set dp[i] = 1 inside outer loop before inner loop, then update.
I'll do:
vector dp(n+1, 0);
for idx...:
i = first_perm[idx];
dp[i] = 1;
for jdx ...:
if (good) dp[i] = max(dp[i], dp[j]+1);
ans = max(ans, dp[i]);
That's fine because dp[i] is being computed for the first time at its position in order (since i appears exactly once in first_perm). So we can set dp[i]=1 initially then update.
Thus we don't need initialization.
Now what about numbers that appear in later permutations but not in first? Actually all numbers 1..n appear exactly once in each permutation, so all numbers appear in first_perm as well. So each i gets processed exactly once.
Thus DP correct.
Now test on another case: n=3, k=2, perms: 1 2 3 and 3 2 1. Should get answer 1. Let's simulate:
first_perm = [1,2,3]
pos1 (for perm1) from reading: Actually for m=0, we read first_perm and also set pos[0][x]=i; that's fine.
Now for m=1, perm2: 3 2 1 => pos[1][3]=0, pos[1][2]=1, pos[1][1]=2.
Now process:
idx0 i=1: dp[1]=1 (no prev)
idx1 i=2: prev j=1; check m=1: pos[1][1]=2, pos[1][2]=1 => 2<1? false -> no update; dp[2]=1.
idx2 i=3: prev j=1: check pos[1][1]=2, pos[1][3]=0 => false; j=2: pos[1][2]=1, pos[1][3]=0 => false; dp[3]=1. ans=1. Good.
What about case where answer >1: n=5, k=2, perms: 1 2 3 4 5 and 2 4 5 3 1? Actually let's test a scenario: perm1: 1 2 3 4 5; perm2: 1 3 5 2 4? Not sure. But DP should handle.
Now, consider k > 2 and different orders. Works.
Now, could there be any case where we need to consider the possibility of subsequence not necessarily following the order of the first permutation? Actually any common subsequence will be increasing in all permutations, including the first. So the order of numbers in the common subsequence will correspond to increasing positions in first permutation as well. So the subsequence corresponds to an increasing sequence of positions in perm1. Thus the numbers in the common subsequence must appear in increasing order of their index in perm1. Therefore the longest chain we compute by DP over numbers sorted by perm1 order is valid. It might be that there exists a chain that is not sorted by perm1? But chain condition includes pos1[x] < pos1[y], so any chain will be sorted by perm1. So DP over perm1 order is fine.
Now, complexity for n=1000 is fine.
Potential pitfalls: Input reading: sometimes there may be leading/trailing spaces. But we use cin.
Now produce final answer.
One more thought: The DP as described might be O(n^2 * k) but could be optimized using BIT / segment tree for k=2 (LIS) but not needed. For k up to 5, the DP approach is the standard one for "Longest Common Subsequence of k permutations".
Actually known solution: LCS of multiple permutations can be solved by DP in O(k * n^2) using pos arrays.
Thus finalize.
But wait, there is a more efficient solution using DP on DAG with adjacency list built by checking conditions? That still O(n^2) but we are okay.
Now, we must consider the possibility of identical numbers? No, numbers are distinct (permutations). So fine.
Thus final code is simple.
I will also add a fast I/O maybe: ios_base::sync_with_stdio(false); cin.tie(NULL);.
Now, let's implement.
Now produce the answer.
But I realize one thing: The approach of iterating over previous indices only checks j that appear earlier in perm1. That's enough. But we must ensure that the DP is correct even if there is a predecessor j that does not appear earlier in perm1? That can't happen because predecessor must satisfy pos1[j] < pos1[i], so j appears earlier in perm1. So covered.
Thus code stands.
Now, verify for k=5. Works.
Now produce final solution.
I'll write the solution explanation as well.
Thus final answer: code in C++.
Now, could there be any memory/performance issues? No.
Now, let's produce final output.
But wait, I should confirm that the DP order must be such that when we process i, all j that are predecessors are processed. Since we iterate by increasing perm1 index, any j with pos1[j] < pos1[i] is processed earlier, correct. So DP is valid.
Now final code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, k;
cin >> n >> k;
vector<vector<int>> pos(k, vector<int>(n+1));
vector<int> first_perm(n);
for (int m = 0; m < k; ++m) {
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (m == 0) first_perm[i] = x;
pos[m][x] = i;
}
}
vector<int> dp(n+1, 0);
int ans = 0;
for (int idx = 0; idx < n; ++idx) {
int v = first_perm[idx];
dp[v] = 1;
for (int jdx = 0; jdx < idx; ++jdx) {
int u = first_perm[jdx];
bool ok = true;
for (int m = 1; m < k; ++m) {
if (pos[m][u] >= pos[m][v]) {
ok = false;
break;
}
}
if (ok) {
dp[v] = max(dp[v], dp[u] + 1);
}
}
ans = max(ans, dp[v]);
}
cout << ans << endl;
return 0;
}
That should be correct.
But wait: In the inner loop we use m from 1 to k-1. That's correct because we skip m=0. However note that pos[0][...] was set from first_perm? Actually we set pos[0][x]=i for the first permutation. So yes.
Now, check for k=1? But constraint says k >= 2. So fine.
Now, answer.
Thus final. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, k;
cin >> n >> k;
// pos[m][x] = index (0‑based) of number x in the m‑th permutation
vector<vector<int>> pos(k, vector<int>(n + 1));
// first_perm stores the first permutation to define the processing order
vector<int> first_perm(n);
for (int m = 0; m < k; ++m) {
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (m == 0)
first_perm[i] = x;
pos[m][x] = i; // 0‑based position
}
}
vector<int> dp(n + 1, 0); // dp[x] = length of longest chain ending at x
int ans = 0;
// Process numbers in the order of the first permutation.
// This guarantees that any possible predecessor j has already been processed.
for (int idx = 0; idx < n; ++idx) {
int v = first_perm[idx];
dp[v] = 1; // chain consisting only of v
// Check all numbers that appear earlier in the first permutation.
for (int jdx = 0; jdx < idx; ++jdx) {
int u = first_perm[jdx];
bool good = true;
// Verify that u is before v in all the other permutations.
for (int m = 1; m < k; ++m) {
if (pos[m][u] >= pos[m][v]) {
good = false;
break;
}
}
if (good) {
dp[v] = max(dp[v], dp[u] + 1);
}
}
ans = max(ans, dp[v]);
}
cout << ans << endl;
return 0;