【PAT A1045】Favorite Color Stripe

Eva is trying to make her own color stripe out of a given one. She would like to keep only her favorite colors in her favorite order by cutting off those unwanted pieces and sewing the remaining parts together to form her favorite color stripe.

It is said that a normal human eye can distinguish about less than 200 different colors, so Eva’s favorite colors are limited. However the original stripe could be very long, and Eva would like to have the remaining favorite stripe with the maximum length. So she needs your help to find her the best result.

Note that the solution might not be unique, but you only have to tell her the maximum length. For example, given a stripe of colors {2 2 4 1 5 5 6 3 1 1 5 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 1 5 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 line contains a positive integer N (≤200) which is the total number of colors involved (and hence the colors are numbered from 1 to N). Then the next line starts with a positive integer M (≤200) followed by M Eva’s favorite color numbers given in her favorite order. Finally the third line starts with a positive integer L (≤10410^4) which is the length of the given stripe, followed by L colors on the stripe. All the numbers in a line a separated by a space.

Output Specification:
For each test case, simply print in a line the maximum length of Eva’s favorite stripe.

Sample Input:

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

思路
今天總算發現做題的方法,其實刷題真的有點像小學的找規律題,如果給你一大串數字叫你找規律,你可能還真找不到,但從小規模的數開始,會發現規律其實並沒有想象中的複雜。OK,我們來想想我們人在處理這種題的時候是怎麼做的,先從小問題開始(以sample input爲例)假設現在只給你一個數也就是2,你怎麼做?第一步自然是去2 3 1 5 6裏面去找有沒有2對吧,發現有那麼說明如果只有一個2,那麼答案就是1,因爲只有1個他想要的color;問題升級,現在有兩個數2 2,現在怎麼做?對於第二個2我們第一步還是去找2是否在她喜歡的color裏面,接下來發現前面也是2,因此長度爲2,到目前爲止看起來是在說廢話,那麼接下來我們來考慮2 2 4 1 5 5 6 3 1 1 5 6的情況,假設我們當前已經走到了最後一個6,第一步仍然是去找6是否在她喜歡的顏色裏面,發現是,那麼我們要求的長度等於多少呢,既然6是在她喜歡的顏色序列排最後,那麼說明我們要求的長度等於排除最後一個6之外的序列中要求的長度加1.那麼如果最後一位的6是1呢,思考一下吧!(答案:分別以2,2 3,2 3 1爲喜歡顏色序列的結果中的最大值+1)

#include <cstdio>
using namespace std;

int main(){
	int colors, M, len, stripe[210], input[10010];
	scanf("%d%d", &colors, &M);
	for(int i = 0; i < M; i++){
		scanf("%d", &stripe[i]);
	}
	scanf("%d", &len);

	//dp[i]用來表示當前位置以stripe數組前i爲喜歡序列的結果
	int dp[210] = {0};
	for(int i = 0; i < len; i++){
		scanf("%d", &input[i]);
		int max = 0;
		for(int j = 0; j < M; j++){
			if(dp[j] > max)
				max = dp[j];
			if(input[i] == stripe[j]){
				dp[j] = max + 1;
				break;
			}
		}
	}

	int ans = 0;
	for(int i = 0; i < M; i++)
		ans = ans < dp[i] ? dp[i] : ans;
	printf("%d\n", ans);

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