题目链接
题目描述
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
结尾无空行
题目大意
给你一串序列,然后再给你若干个颜色,问你按给你颜色的顺序里序列的最长长度
解题思路
转化为最长不上升子序列来做
首先记录一下这个给出颜色出现的位置,
将颜色序列转化为出现位置的序列
拿题目中的例子举例
给定的序列 2 3 1 5 6
目标的序列 2 2 4 1 5 5 6 3 1 1 5 6
将给定的序列按照map对应下标
数据 对应下标
2 1
3 2
1 3
5 4
6 5
然后将给定的序列在目标序列中出现过得保留,其他的元素剔除,并按照下标进行存储
for(int i=0;i<l;i++){
cin>>temp;
if(book[temp]){ //只当temp在给定序列出现过得时候cnt++
a[cnt++]=book[temp];
}
}
所以目标序列就变成了
1 1 3 4 4 5 2 3 3 4 5
然后求这个序列的最长不上升子序列就可以了
题解
#include<bits/stdc++.h>
using namespace std;
int book[205],a[10005],dp[10005];
int main(){
int n,m,l;
cin>>n>>m;
int temp;
for(int i=1;i<=m;i++){
cin>>temp;
book[temp]=i;
}
int cnt=0;
cin>>l;
for(int i=0;i<l;i++){
cin>>temp;
if(book[temp]){
a[cnt++]=book[temp];
}
}
fill(dp,dp+10005,1);
int mmax=0;
for(int i=0;i<cnt;i++){
for(int j=0;j<i;j++){
if(a[j]<=a[i]){
dp[i]=max(dp[i],dp[j]+1);
}
}
mmax=max(mmax,dp[i]);
}
cout<<mmax;
}