题目:
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 6Sample Output:
7思路:
这道题我只想到用递归的方法:
在当前节点:
1)如果该点颜色是最后一个颜色,那么搜索该点及之后的最后颜色个数,返回长度;
2)如果该点颜色搜索不是最后一个颜色:
2.1)搜索后面序列中最近的该点颜色的点,长度加1,继续在后面序列中搜索该点颜色;
2.2)在后面序列中换搜索下一个颜色
以上两种情况取最大值
这样的做法繁琐,最高只拿到了24分,有两个测试点超时。
最后是看:
http://blog.csdn.net/apie_czx/article/details/48208793
做的做法。具体思路看该网页。
代码:
#include<iostream>
using namespace std;
int main()
{
int N, M, L;
int fav_order[201] = { 0 };
int stripe[10000] = { 0 };
int max_len[201] = { 0 };
int i,c;
cin >> N >> M;
for (i = 1; i <= M; ++i)
{
cin >> c;
fav_order[c] = i;
}
cin >> L;
for (i = 0; i < L; ++i)
{
cin >>c;
stripe[i] = fav_order[c]; //映射
}
//找出不递减的最大序列
int tmp,j;
for (i = 0; i < L; ++i)
{
tmp = 0;
if (stripe[i]) //是需要的颜色
{
for (j = 1; j <=stripe[i]; ++j)
{
if (tmp < max_len[j]) //找到在该颜色之前累计最大的颜色
tmp = max_len[j];
}
max_len[stripe[i]] = tmp + 1;
}
}
int m_len = 0;
for (i = 1; i <= M; ++i)
{
if (m_len < max_len[i])
m_len = max_len[i];
}
cout << m_len << endl;
system("pause");
return 0;
}