1045お気に入りのカラーストライプ(30ポイント)[要素が繰り返される最長共通部分列]

トピック:
ここに画像の説明を挿入

6
5 2 3 1 5 6
12 2 2 4 1 5 5 6 3 1 1 5 6

サンプル出力:

7

アイデア:
古典的な最長共通部分列モデルの2つのシーケンス要素は、1対1で一致する必要がありますが、この質問では、共通部分で繰り返し要素を使用できます。伝達方程式の文言を変更する必要がある:
例えば:で「AA」と「AB」dp[2][2]してもよいdp[2][1]、で「AB」及び「AA」を得るためにdp[2][2]形成されていてもよいdp[1][2]得るため
ときの結果を得ることができますA[i]!=B[j]時間、dp[i][j]=max(dp[i-1][j],dp[i][j-1])
ACコードは次のとおりです。

#include<iostream>
#include<cstdio>

using namespace std;
const int maxn = 210; 
const int maxx = 10000;
int dp[maxn][maxx];
int a[maxn],b[maxx];
int main()
{
    
    
	int n;
	cin >> n;
	for(int i = 1; i <= n; i++)
	{
    
    
		cin >> a[i];
	}
	int x;
	cin >> x;
	for(int i = 1;i <= x; i++)
	{
    
    
		cin >> b[i];
	}

	for(int i = 0; i <= n; i++)
	{
    
    
		dp[i][0] = 0;
	}
	for(int j = 0; j <= x; j++)
	{
    
    
		dp[0][j] = 0;
	}

	for(int i = 1; i <= n; i++)
	{
    
    
		for(int j = 1; j <= x; j++)
		{
    
    
			int MAX = max(dp[i][j-1],dp[i-1][j]);
			if(b[j] == a[i])
			{
    
    
				dp[i][j] = MAX+1;
			}
			else
			{
    
    
				dp[i][j] = MAX;
			}
		}
	}
	cout << dp[n][x];
	return 0;
}

おすすめ

転載: blog.csdn.net/moumoumouwang/article/details/112427114