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 6Sample Output:
7
题目抽象出来就是寻找两个序列的最长公共子序列, 但是公共部分允许元素重复出。
分析:
是最长公共子序列(LCS,Longest Common Subsequence)的变种-公共部分可以元素重复。
代码:
因为可以横着和竖着转移了。其实只需要从dp[i-1][j]和dp[i][j-1]寻找最大者就可以了,不需要考虑dp[i-1][j-1]。附上我的代码:
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[201];
int b[10001];
int dp[201][10001]={0};
int n,m,l;
void lcs()
{
for(int row=1;row<=m;row++)
for(int col=1;col<=l;col++)
{
int tmp=max(dp[row-1][col],dp[row][col-1]);
if(a[row]==b[col]) dp[row][col]=tmp+1;
else dp[row][col]=tmp;
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
cin>>a[i];
cin>>l;
for(int i=1;i<=l;i++)
cin>>b[i];
lcs();
cout<<dp[m][l];
return 0;
}
再附上一个别人LIS的代码
先把喜欢的序列给编号:
喜欢颜色序列:2 3 1 5 6
喜欢颜色编号:1 2 3 4 5
然后把它对应到已有序列上面去
原颜色序列 2 2 4 1 5 5 6 3 1 1 5 6
最后的max:[1] [2] 0 [3] [4] [5] [6] [3] [4] [5] [6] [7]
映射之后的: 1 1 0 3 4 4 5 2 3 3 4 5
因为我们知道它一定要按照序列排,也就是说最后的序列一定要去递增的
时间复杂度是O(M*L)。
AC代码: