Codeforces 463D Gargari and Permutations DP(LCS变形)

题意:k个1~n的排列,求这k个排列的LCS.k<=5,n<=1000.

法1:
因为序列为排列,设dp[x]以x结尾能得到最长的LCS.
当x出现k次时 说明x能作为结尾 枚举能接在其前面的数即可 O(k*n^2)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e3+20;
int dp[N],a[N][N],n,k,pos[N][N],cnt[N];
vector<int> ans;
int main()
{
	while(cin>>n>>k)
	{
		ans.clear();
		for(int i=1;i<=k;i++)
			for(int j=1;j<=n;j++)
				scanf("%d",&a[i][j]),pos[i][a[i][j]]=j;
		memset(dp,0,sizeof(dp));
		memset(cnt,0,sizeof(cnt));
		ans.push_back(0);
		int res=0;
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=k;j++)
			{
				int x=a[j][i];
				cnt[x]++;
				if(cnt[x]==k)
				{
					for(int p=0;p<ans.size();p++)
					{
						int y=ans[p],flag=1;
						for(int q=1;q<=k;q++)
						{
							if(pos[q][y]>=pos[q][x])
								flag=0;
						}
						if(flag)
							dp[x]=max(dp[x],dp[y]+1),res=max(res,dp[x]);
					}
					ans.push_back(x);		
				}	
			
			}
		}
		cout<<res<<endl;
	}
	return 0;
}
/*
5 4
1 3 5 4 2
2 3 5 1 4
1 2 4 3 5
5 3 1 4 2
*/

法2:
n<=1000,i能放在j前面 则i->j连接一条边,0为起点,跑一遍BFS即可O(M+k*n^2)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值