Question: 1 ~ K of N (2 <= k <= 5), the longest common subsequence is required.
Practice: DP [I] indicates the length of the longest common subsequence ending with I. Since each number can only appear once in an arrangement, we use a two-dimensional array POS [I] [J] to indicate the position where the number J appears in row I, and then use an array CNT [I] to record how many times I appears; when the number of I appears K times, it indicates that a public subsequence can be formed at the end of this number, then DP [I] = max (DP [J] + 1), where I, j meets the requirements of POS [u] [I]> POS [u] [J] (1 <= u <= K). Of course, to save time, we can store the subscript of the previously calculated DP [I] value in the vector, so that we only need to traverse this vector to find the qualified number.
Code:
#include <iostream>#include <cstdio>#include <vector>#include <algorithm>#define N 1010using namespace std;int pos[6][N],cnt[N],a[6][N],dp[N];vector<int> q;int main(){ int n,k,ans=0; scanf("%d%d",&n,&k); for(int i=0;i<k;i++) for(int j=0;j<n;j++) scanf("%d",&a[i][j]); for(int i=0;i<n;i++) for(int j=0;j<k;j++){ int cur=a[j][i]; pos[j][cur]=i; cnt[cur]++; if(cnt[cur]==k){ if(q.size()==0) dp[cur]=1; else for(int kk=0;kk<q.size();kk++){ bool flag=false; for(int l=0;l<k;l++) if(pos[l][cur]<pos[l][q[kk]]) {flag=true;break;} if(!flag) dp[cur]=max(dp[cur],dp[q[kk]]+1); else dp[cur]=max(dp[cur],1); } ans=max(ans,dp[cur]); q.push_back(a[j][i]); } } cout<<ans<<endl; return 0;}
Codeforces 463d. gargari and permutations [DP]