Gargari and Permutations
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
4 3
1 4 2 3
4 1 2 3
1 2 4 3
3
Note
The answer for the first test sample is subsequence [1, 2, 3].
sol:求m个序列的lcs,似乎看上去很难得样子,实际上想到dp状态就不难了,dp[i]表示以数字 i 结尾的m个序列的lcs长度,然后判断一下是否所有数字 j 都在 i 之前就可以转移了
#include <bits/stdc++.h> using namespace std; typedef int ll; inline ll read() { ll s=0; bool f=0; char ch=' '; while(!isdigit(ch)) { f|=(ch=='-'); ch=getchar(); } while(isdigit(ch)) { s=(s<<3)+(s<<1)+(ch^48); ch=getchar(); } return (f)?(-s):(s); } #define R(x) x=read() inline void write(ll x) { if(x<0) { putchar('-'); x=-x; } if(x<10) { putchar(x+'0'); return; } write(x/10); putchar((x%10)+'0'); return; } #define W(x) write(x),putchar(' ') #define Wl(x) write(x),putchar(' ') const int N=1005; int n,m,a[10][N],Pos[10][N]; int dp[N]; int main() { int i,j,k; R(n); R(m); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { R(a[i][j]); Pos[i][a[i][j]]=j; } } dp[a[1][1]]=1; for(i=2;i<=n;i++) { for(j=1;j<i;j++) { bool Flag=1; for(k=2;k<=m&&Flag;k++) if(Pos[k][a[1][j]]>Pos[k][a[1][i]]) Flag=0; if(Flag) dp[a[1][i]]=max(dp[a[1][i]],dp[a[1][j]]+1); } if(!dp[a[1][i]]) dp[a[1][i]]=1; } int ans=1; for(i=1;i<=n;i++) ans=max(ans,dp[i]); Wl(ans); return 0; } /* Input 4 3 1 4 2 3 4 1 2 3 1 2 4 3 Output 3 */