zoukankan      html  css  js  c++  java
  • CodeForces

    Discription

    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
    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].

       一开始看的时候有点懵,,,,多个串的最长公共子序列 我好像只会后缀自动机啊hhhhh,这个题字符集大小还蛮大的emmmm(事实上是我根本不想写SAM   hhh)。

        但是这个题有特殊性质啊,每个串都是一个排列,也就是说每个数在k个串里只有一种组合方式,所以我们直接在DAG上dp就好了。

    #include<bits/stdc++.h>
    #define ll long long
    using namespace std;
    const int maxn=1005;
    int P[maxn][5],n,now,k,to[maxn*1000];
    int ne[maxn*1000],hd[maxn],num,ans,F[maxn];
    inline void add(int x,int y){ to[++num]=y,ne[num]=hd[x],hd[x]=num;}
    void dp(int x){
    	if(F[x]) return;
    	for(int i=hd[x];i;i=ne[i]) dp(to[i]),F[x]=max(F[x],F[to[i]]);
    	F[x]++;
    }
    int main(){
    	scanf("%d%d",&n,&k);
    	for(int i=0;i<k;i++)
    	    for(int j=1;j<=n;j++) scanf("%d",&now),P[now][i]=j;
    	for(int i=1;i<=n;i++)
    	    for(int j=1,o;j<=n;j++){
    	    	for(o=0;o<k;o++) if(P[i][o]>=P[j][o]) break;
    	    	if(o==k) add(i,j);
    		}
    	
    	for(int i=1;i<=n;i++) dp(i),ans=max(ans,F[i]);
    	printf("%d
    ",ans);
    	return 0;
    }
    

      

  • 相关阅读:
    libusbwin32
    KMP
    windows.h
    iomanip
    C++继承
    LIST
    fstream
    VS2010中调试c++程序的方法
    sstream
    char 与char* 字符串与字符
  • 原文地址:https://www.cnblogs.com/JYYHH/p/8946761.html
Copyright © 2011-2022 走看看