天天看點

PAT 1045. Favorite Color Stripe (30) 1045. Favorite Color Stripe (30)

1045. Favorite Color Stripe (30)

時間限制 200 ms

記憶體限制 65536 kB

代碼長度限制 16000 B

判題程式 Standard 作者 CHEN, Yue

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 (<=10000) which is the length of the given stripe, followed by L colors on the stripe. All the numbers in a line are 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
      

Sample Output:

7
      

這是一道DP問題。首先按照Eva喜歡的順序對stripe上的顔色進行指派,不在Eva喜歡顔色範圍内的直接删去。例如如果Eva喜歡的順序是425,那麼stripe上所有顔色為4的替換為1,顔色為2的替換為2,顔色為5的替換3. 也就是賦予每個點對應的權值。

然後就是動态規劃問題了,從起始點開始求出每個點的最大長度。假設有i , j 兩個點且i<j,那麼 i 可達j 當且僅當 j 的權值≥ i 的權值。 對 j 來說周遊所有位于 j 之前的可達 j 的點,取其中最大長度+1就是j 的最大長度了。 

代碼如下:

#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <set>
using namespace std;

int main(){
	int N,M,L,i;
	int order[201];
	memset(order,0,sizeof(order));
	cin>>N>>M;
	for(i=1;i<=M;i++)
	{
		int temp;
		cin>>temp;
		order[temp]=i;
	}
	vector<int> stripe;
	cin>>L;
	for(i=0;i<L;i++)
	{
		int temp;
		cin>>temp;
		if(order[temp]>0)
			stripe.push_back(order[temp]);
	}
	int size=stripe.size();
	if(size==0)
	{
		cout<<0<<endl;
		return 0;
	}
	int result[10000];
	for(i=0;i<10000;i++)
		result[i]=1;
	for(i=1;i<size;i++)
		for(int j=0;j<i;j++)
			if(stripe[i]>=stripe[j])
				if(result[j]+1>result[i])
					result[i]=result[j]+1;
	int maxLen=0;
	for(i=0;i<size;i++)
		if(result[i]>maxLen)
			maxLen=result[i];
	cout<<maxLen;
}
           

繼續閱讀