Codeforces #264(div 2)D.Gargari and Permutations

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.

Sample test(s)
input
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].


大致思想:dp[i]代表以第一行的第i个数末尾为子序列的终点所能构成的最长子序列长度,由于每一行1-n一定会出现一次,如果第一行的a排在b前面,且之后的每一行a都在b前面,那么dp[a]=max(dp[a],dp[b]) 如果用一个数组记录下每一行中每一个数的位置,就可以很轻松地判断某一行中两个数之间的位置关系了。
难度:3 不算很难的dp 但是对于我这样的新手来说也不简单。代码虽短,但是写这一段花了很久,因为各种细节都能错= =。总之是一道不错的题,值得记录下来。


#include<bits/stdc++.h>
using namespace std;
int main(){
	int m,n,i,j,k,t,s;
	int a[6][2005]={};
	int p[6][2005]={};
	while(cin>>n>>k){
		int dp[2005]={};
		for(i=1;i<=k;i++){
			for(j=1;j<=n;j++){
				cin>>a[i][j];
				p[i][a[i][j]]=j;
			}
		}
		for(i=1;i<=n;i++){
			dp[i]=1;
			for(j=1;j<i;j++){
				for(s=2;s<=k;s++){
					if(p[s][a[1][j]]>=p[s][a[1][i]]) goto l;
				}
				dp[i]=max(dp[i],dp[j]+1);
				l:;
			}
		}
		int ans=0;
		for(i=1;i<=n;i++){
			ans=max(ans,dp[i]);
		}
		cout<<ans<<endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值