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?
You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Input
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
inputCopy
4 3
1 4 2 3
4 1 2 3
1 2 4 3
outputCopy
3
Note
The answer for the first test sample is subsequence [1, 2, 3].
给 k 个串求最长公共子序列;
以第一个为基准,确定每一个数的位置,如果第一行的a排在b前面,且之后的每一行a都在b前面,那么dp[a]=max(dp[a],dp[b]) ,用一个数组记录下每一行中每一个数的位置,就可以判断某一行中两个数之间的位置关系了。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define maxn 200005
const int mod=1e9+7;
#define eps 1e-5
#define pi acos(-1.0)
ll quickpow(ll a,ll b)
{
ll ans=1;
while(b){
if(b&1){
ans=ans*a;
}
a=a*a;
b>>=1;
}
return ans;
}
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
int a[6][1004];
int p[6][1004];
int dp[1005];
int main()
{
ios::sync_with_stdio(false);
int n,k;
cin>>n>>k;
int i,j;
for(i=1;i<=k;i++){
for(j=1;j<=n;j++){
cin>>a[i][j];
p[i][a[i][j]]=j;
}
}
int ans=0;
for(i=1;i<=n;i++){
dp[i]=1;
for(j=1;j<i;j++){
for(int s=2;s<=k;s++){
if(p[s][a[1][i]]<=p[s][a[1][j]])goto x;
}
dp[i]=max(dp[i],dp[j]+1);
x:;
}
}
for(i=1;i<=n;i++)ans=max(ans,dp[i]);
cout<<ans<<endl;
return 0;
}