D. Gargari and Permutations dp + LCS ( dp 好题 )

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值