Codeforces 463d. gargari and permutations [DP]

Source: Internet
Author: User
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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.