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 (≤104) 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
Sample Output:
7
题意:给你一个自己喜欢的序列顺序,从目标序列中挑出按自己喜欢顺序的最大长度。
注意点:
1.段错误: 数组开小了。
2.有可能目标序列中含有自己不喜欢的元素,我的做法是直接剔除,记录被删掉的数的个数cnt,拿目标序列的长度-cnt,就是后面计算dp的范围。
3.运行超时:我第一次是用map,结果超时。第二次用数组,算法笔记说:由于计算过程中对数组都是连续操作的,使得cache命中率高,省时间。
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
const int r=10005;
int a[r];
int dp[r];
int main(){
int n,m,l,i,j,t,max=-1,cnt=0,k=0;
int s[205];
fill(s,s+205,-1);
scanf("%d %d",&n,&m);
for(i=0;i<m;i++){
scanf("%d",&t);
s[t]=i;
}
scanf("%d",&l);
for(i=0;i<l;i++)
{
scanf("%d",&t);
if(s[t]==-1){
cnt++;
continue;
}
else
{
a[k++]=t;
}
}
l=k;
for(i=0;i<l;i++){
dp[i]=1;
for(j=0;j<i;j++){
// cout<<a[i]<<" "<<a[j]<<" "<<s[a[i]]<<" "<<s[a[j]]<<endl;
if(s[a[i]]>=s[a[j]]&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
}
}
if(dp[i]>max){
max=dp[i];
}
}
printf("%d\n",max);
return 0;
}