CodeForces - 463D Gargari and Permutations (多行公共子序列的DP)

D. Gargari and Permutations
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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
Input
Copy

4 3
1 4 2 3
4 1 2 3
1 2 4 3

Output

3

Note

The answer for the first test sample is subsequence [1, 2, 3].

解析:最长公共子序列一定是在第一行中存在的,所以我们可以枚举第一行的下标j,然后枚举其之前的下标p,那么合适满足条件呢,在剩下的行数中,这两个相对应的数字的先后关系不变,这样我们就可以进行更新了,dp[j]=max(dp[j],dp[p]+1);
注意dp数组初始值为1,即包含自身
具体代码中有注释

#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define pb push_back
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,b,a) for(int i=b;i>=a;i--)
using namespace std;
const int N=1e5+100;
int arr[N];
int n,k;
int position[5][1000];//记录position[i][j]记录第i行中,数字j出现的位置。
int a[5][1000];//记录数列
int dp[1000];//dp[i]表示,以下标i结尾的最长公共子序列长度。
int main()
{
    cin>>n>>k;
    for(int i=0;i<k;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>a[i][j];
            position[i][a[i][j]]=j;
        }
    }
    int ans=0;
    for(int j=0;j<n;++j)
    {//对于第一行中的下标j
        dp[j]=1;
        for(int p=0;p<j;++p)
        {//对于第一行以(j之前的每个点) 结尾的最长序列,判断j可不可以加进去
            int i;
            for(i=1;i<k&&position[i][a[0][p]]<position[i][a[0][j]];i++);//如果这几行a[0][p]的位置都在a[0][j]的前面,则满足条件
            if(i==k)
                dp[j]=max(dp[j],dp[p]+1);//maxn表示以这个点结尾(不包括这个点)的最长公共子序列的长度
        }
        ans=max(ans,dp[j]);//求每一点dp值最大的一个。,也可以之后遍历解决
    }
    cout<<ans<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/ffgcc/p/10546474.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值