题目描述
Eva is trying to make her own color stripe out of a givenone. She would like to keep only herfavorite colors in her favorite order by cutting off those unwanted pieces andsewing the remaining parts together to form her favorite 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 original stripe could be verylong, and Eva would like to have the remaining favorite stripe with the maximumlength. So she needs your help to findher the best result.
Note that the solution might not be unique, but you only have to tell her themaximum length. For example, given astripe 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 15 5 6 6}, and {2 2 3 1 1 5 6}.
输入描述:
Each input file contains one test case. For each case, the first line contains apositive integer N (<=200) which is the total number of colors involved (andhence the colors are numbered from 1 to N). Then the next line starts with a positive integer M (<=200) followedby M Eva's favorite color numbers given in her favorite order. Finally the third line starts with a positiveinteger L (<=10000) which is the length of the given stripe, followed by Lcolors on the stripe. All the numbers ina line are separated by a space.
输出描述:
For each test case, simply print in a line the maximum length ofEva's favorite stripe.
输入例子:
6
5 2 3 1 5 6
12 2 2 4 1 5 5 6 3 1 1 5 6
输出例子:
7
我一看到这一题首先想到的就是最长递增子序列,只不过这里的递增顺序是颜色在eve喜好序列的排序,
这一题还有一个加速的方法就是查询输入的数字是否在EVE的爱好序列里面,如果不在里面,这个数字可以忽略不计,
这里还需要注意一点,如果使用哈希表来进行爱好颜色和id之间的转换的话,可能会超时,因为哈希表和线性表的查询效率差的不是一星半点,以后在做题的时候,当题目中给的索引是数字的时候,尽量不用哈希表,而使用线性表,能够提高效率
#include<iostream>
#include<algorithm>
using namespacestd;
inttheStoreHead[10003];
int dp[10003] ={ 0 };
int theEves[203]= { 0 };
int main() {
int N;
int M,tmp;
int storeNum;
cin >> N >> M;
for (int i = 1; i <= M; i++)
{
cin >> tmp;
theEves[tmp] = i;
}
cin >> storeNum;
for (int i = 0; i < storeNum; i++)
{
cin >> theStoreHead[i];
}
int theMaxLength = -1;
for (int i = 1; i <= storeNum; i++)
{
if (theEves[theStoreHead[i-1]]==0)
continue;
else dp[i] = 1;
tmp = theEves[theStoreHead[i-1]];
for (int j = i - 1; j >= 1; j--)
{
if (theEves[theStoreHead[j -1]] == 0) continue;
if (theEves[theStoreHead[j-1]]<= tmp)
{
dp[i] = max(dp[j] + 1,dp[i]);
theMaxLength =max(theMaxLength, dp[i]);
}
}
}
cout << theMaxLength;
return 0;
}