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].
思路:找出k个序列中都存在的最长的序列。那么这个串中的元素在这k个序列的相对位置都是相同的,那么我们找出在所有的数对(x,y),这种数对的特性是在k个序列中x都在y的前面,这样的序列,我们给他们建一条边。然后记忆化搜索跑图去得到一个最大值就可以了。
代码如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxx=1e6+100;
const int maxm=1e3+100;
struct edge{
int to,next;
}e[maxx<<1];
int a[maxx],head[maxx<<1],dp[maxm];
int n,m,tot;
inline void init()
{
tot=0;
memset(head,-1,sizeof(head));
memset(dp,-1,sizeof(dp));
}
inline void add(int u,int v)
{
e[tot].to=v,e[tot].next=head[u],head[u]=tot++;
}
inline int dfs(int u)
{
if(dp[u]!=-1) return dp[u];
dp[u]=1;
int sum=0;
for(int i=head[u];i!=-1;i=e[i].next)
{
int to=e[i].to;
sum=max(sum,dfs(to));
}
dp[u]+=sum;
return dp[u];
}
int main()
{
scanf("%d%d",&n,&m);
map<pair<int,int>,int> mp;
init();
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++) scanf("%d",&a[j]);
for(int x=1;x<=n;x++)
for(int y=x+1;y<=n;y++) mp[make_pair(a[x],a[y])]++;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++) if(mp[make_pair(i,j)]==m) add(i,j);
int _max=0;
for(int i=1;i<=n;i++) _max=max(_max,dfs(i));
cout<<_max<<endl;
return 0;
}
努力加油a啊,(o)/~