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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章