PAT A 1045. Favorite Color Stripe (30)

题目

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;
}


 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值