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}.
解题思路:
题目的意思是喜欢的序列是S1,所给序列S2,要从S2中先去掉S1中不存在数字,最后求出剩下的S2中按照S1顺序排列的最大长度。
将S2中的所有元素替换成S1中的下标比如;
S1{2 3 1 5 6}
2 | 3 | 1 | 5 | 6 |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
S2{2 2 1 5 5 6 3 1 1 5 6}
2 | 2 | 1 | 5 | 5 | 6 | 3 | 1 | 1 | 5 | 6 |
---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 2 | 3 | 3 | 4 | 1 | 2 | 2 | 3 | 4 |
可以看到 题目要求就转变为求{0 0 2 3 3 4 1 2 2 3 4}的序列中最长不下降子序列
AC代码
#include <iostream>
#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
map<int,int> mp;
map<int,bool> vis;
int nums[10010];
int main()
{
int n,m,x;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d",&x);
mp[x]=i;
vis[x]=1;
}
scanf("%d",&m);
memset(nums,0,sizeof(nums));
int index=0;
for(int i=0;i<m;i++){
scanf("%d",&x);
if(vis[x]){
nums[index++]=mp[x];
}
}
int dp[index],ans=0;
for(int i=0;i<index;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(nums[i]>=nums[j]&&dp[j]+1>dp[i])
dp[i]=dp[j]+1;
}
ans=max(ans,dp[i]);
}
printf("%d\n",ans);
return 0;
}