PAT(贪心)——1045. Favorite Color Stripe (30)
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
题目大意:
eva有M种喜欢的按顺序排列的颜色,给出长度为L的颜色序列,要求去掉不喜欢的颜色之后按照喜欢顺序排列的子序列,求最长子序列的长度。
题目解析:
可以这样理解,例如喜欢的颜色顺序是{2 3 1 5 6},分析到颜色1时,1最大的长度就是前面2,3,1里面最大的长度+1.。
具体代码:
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 205
int pre[MAXN];//pre[i]表示i颜色当前最大的长度
int list[MAXN];//喜欢的顺序
int order[MAXN];//某颜色对应的位置
int main()
{
fill(pre,pre+MAXN,-1);
freopen("data.in","r",stdin);
int n,m,l;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d",&list[i]);
order[list[i]]=i;
pre[list[i]]=0;
}
scanf("%d",&l);
for(int i=0;i<l;i++){
int num;
scanf("%d",&num);
if(pre[num]<0)
continue;
int max=-1;
for(int j=0;j<=order[num];j++)
if(pre[list[j]]>max)
max=pre[list[j]];
pre[num]=max+1;
}
int maxlen=0;
for(int i=0;i<m;i++)
if(pre[list[i]]>maxlen)
maxlen=pre[list[i]];
printf("%d",maxlen);
return 0;
}