本文主要是介绍【PAT 1045】 Favorite Color Stripe 最长公共子序列LCS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 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 6Sample Output:
7
题目抽象出来就是寻找两个序列的最长公共子序列, 但是公共部分允许元素重复出。
分析:
是最长公共子序列(LCS,Longest Common Subsequence)的变种-公共部分可以元素重复。
代码:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>using namespace std;//此代码使用前,需删除下面两行+后面的system("PAUSE")
ifstream fin("in.txt");
#define cin finint like[201]={0};
int given[10001]={0};
int len[201][10001]={0};int LCS(int row,int col)
{int i,j;int max;for(i=1;i<=row;i++){for(j=1;j<=col;j++){max = len[i-1][j-1];if(max < len[i][j-1])max = len[i][j-1];if(max < len[i-1][j])max = len[i-1][j]; //先求出左边、上边、左上边 三个值中的最大值if(like[i]==given[j]){ //如果相等,则将最大值+1len[i][j] = max+1;}else{len[i][j] = max;} }}return len[row][col];
}int main()
{int n,m,l;cin>>n>>m;int i;for(i=0;i<m;i++)cin>>like[i+1];cin>>l;for(i=0;i<l;i++)cin>>given[i+1];cout<<LCS(m,l)<<endl;system( "PAUSE");return 0;
}
这篇关于【PAT 1045】 Favorite Color Stripe 最长公共子序列LCS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!