Gargari and Permutations CodeForces - 463D(建图+记忆化搜索)

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)/~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值