Codeforces 463D Gargari and Permutations(求k个序列的LCS)

时间:2023-03-08 19:30:33
Codeforces 463D Gargari and Permutations(求k个序列的LCS)

题目链接:http://codeforces.com/problemset/problem/463/D

题目大意:
给你k个序列(2=<k<=5),每个序列的长度为n(1<=n<=1000),每个序列中的数字分别为1~n,求着k个序列的最长公共子序列是多长?
解题思路:
由于每个序列的数字分别为1~n即各不相同,所以可以用pos[i][j]记录第i个序列中j的位置。
设dp[i]表示以i结尾的最长公共子序列长度,那么我们可以按顺序遍历第一个序列的位置i,
再在第一个序列中枚举位置j(j<i),然后遍历其他序列,如果对于每个序列k都满足pos[k][a[1][i]]>pos[k][a[1][j]],
那么说明a[1][i]可以接在a[1][j]后面,dp[a[1][i]]=max(dp[a[1][i],dp[a[1][j]]+1)。
这里说明一下:按顺序遍历是为了保证dp[a[1][j]]是已经求好了的,如果直接按值来遍历则会出现前面的dp值未求好的情况。

代码:

 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<string.h>
#include<cctype>
#include<math.h>
#include<stdlib.h>
#include<stack>
#include<queue>
#include<set>
#include<map>
#define lc(a) (a<<1)
#define rc(a) (a<<1|1)
#define MID(a,b) ((a+b)>>1)
#define fin(name) freopen(name,"r",stdin)
#define fout(name) freopen(name,"w",stdout)
#define clr(arr,val) memset(arr,val,sizeof(arr))
#define _for(i,start,end) for(int i=start;i<=end;i++)
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef long long LL;
const int N=2e3+;
const LL INF64=1e18;
const int INF=0x3f3f3f3f;
const double eps=1e-; int dp[N],a[][N],pos[][N];//dp[i]表示以i结尾的最长公共子序列长度 int main(){
FAST_IO;
int n,q;
cin>>n>>q;
for(int i=;i<=q;i++){
for(int j=;j<=n;j++){
cin>>a[i][j];
pos[i][a[i][j]]=j;
}
} for(int i=;i<=n;i++){
dp[a[][i]]=;
for(int j=;j<i;j++){
int t1=a[][i],t2=a[][j];
bool flag=true;
for(int k=;k<=q;k++){
if(pos[k][t1]<=pos[k][t2]){
flag=false;
break;
}
}
if(flag)
dp[t1]=max(dp[t1],dp[t2]+);
}
} int ans=;
for(int i=;i<=n;i++){
ans=max(ans,dp[i]);
}
cout<<ans<<endl;
return ;
}