PAT A 1045. Favorite Color Stripe (30)

2725 ワード

タイトル
Eva is trying to make her own color stripe out of a given one. She wouldlike to keep only her favorite colors in her favorite order by cutting offthose unwanted pieces and sewing the remaining parts together to form herfavorite color stripe.
It is said that a normal human eye can distinguish about less than 200different colors, so Eva's favorite colors are limited. However the originalstripe could be very long, and Eva would like to have the remaining favoritestripe with the maximum length. So she needs your help to find her the bestresult.
Note that the solution might not be unique, but you only have to tell herthe maximum length. For example, given a stripe of colors {2 2 4 1 5 5 6 3 1 15 6}. If Eva's favorite colors are given in her favorite order as {2 3 1 5 6},then she has 4 possible best solutions {2 2 1 1 1 5 6}, {2 2 1 5 5 5 6}, {2 2 15 5 6 6}, and {2 2 3 1 1 5 6}.
Input Specification:
Each input file contains one test case. For each case, the first linecontains a positive integer N (<=200) which is the total number of colorsinvolved (and hence the colors are numbered from 1 to N). Then the next linestarts with a positive integer M (<=200) followed by M Eva's favorite colornumbers given in her favorite order. Finally the third line starts with apositive integer L (<=10000) which is the length of the given stripe,followed by L colors on the stripe. All the numbers in a line are separated bya space.
Output Specification:
For each test case, simply print in a line the maximum length of Eva'sfavorite stripe.
Sample Input:
6
5 2 3 1 5 6
12 2 2 4 1 5 5 6 3 1 1 5 6
Sample Output:
7
 
ダイナミックプランニング
c[i]i番目のカラーバーの色、f[j]j番目の好きな色、n(i,j)からi番目のカラーバーは、前のj番目の好きな色だけで取得できる最長の長さ
再帰式n(i,j)=max(n(i,j−1),n(i−1,j)+if(c[i]=f[j]))
ボトムアップ計算
 
コード:
#include <iostream>
using namespace std;

//    
int main()
{
	int n;	//    ,    (       ……)
	cin>>n;
	int i,j;
	int m,fav[200];	//       ,       
	cin>>m;
	for(i=0;i<m;i++)
		scanf("%d",&fav[i]);
	int l,*colour;	//     ,      
	cin>>l;
	colour=new int[l];
	for(i=0;i<l;i++)
		scanf("%d",&colour[i]);

	int *data;	//          j           ( 0    )
	data=new int[m];
	if(colour[0]==fav[0])	//   
		data[0]=1;
	else
		data[0]=0;
	
	for(i=1;i<l;i++)	//      
		for(j=0;j<m;j++)
			if(colour[i]==fav[j])	// i     j      
				data[j]++;
			else if(j!=0&&data[j-1]>data[j])	//  ,j  0(          ),  j-1           j  
				data[j]=data[j-1];				

	cout<<data[m-1];

	delete[] data;

	return 0;
}