【PAT】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}.

翻译:Eva试着从给出的布条中选出她自己的彩色布条。她想要仅仅保留按照她最喜欢的顺序排列的她喜欢的颜色,并且剪掉那些不喜欢的部分再将剩下的部分缝在一起来组成她最喜欢的彩色布条。所以她需要你的帮助来找出最好的结果。
注意结果可能不为1,但是你只需要告诉她最大的长度。举个例子,给你一个 {2 2 4 1 5 5 6 3 1 1 5 6}.的彩色布条。如果Eva最喜欢的顺序排列的最喜欢的颜色为{2 3 1 5 6},这样她有4种可能的最佳方案 {2 2 1 1 1 5 6}, {2 2 1 5 5 5 6}, {2 2 1 5 5 6 6}, 和{2 2 3 1 1 5 6}。

INPUT FORMAT

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.

翻译:每个输入文件包含一组测试数据。对于每组测试数据,第一行包括一个正整数N(<=200) 代表颜色的总个数(并且颜色被标记为1到N)。接着下一行开始为一个正整数M(<=200) ,接着是M个按照EVA最喜欢的顺序排的她最喜欢的颜色编号。最后第三行的第一个正整数L (<=10000) 代表给出的布条长度,跟着L个布条上的颜色。一行内所有的数字都用空格隔开。

OUTPUT FORMAT

For each test case, simply print in a line the maximum length of Eva’s favorite stripe.

翻译:对于每组测试数据,只输出一行Eva的最喜欢的布条的最大长度。


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


解题思路

这道题是典型的贪心问题,可以类比拦截导弹问题,首先先将每个数字最先出现的编号保存到hash数组里。然后,假设现在输入的是a且hash[a]=ha,ha>0,则状态转移方程为:dp[i]=max(dp[i],dp[j]+1)。j为ha—1,i为M—ha。从大到小的原因是如果先更新dp[ha],会导致后面的计算出现错误。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
int N,M,L;
int dp[210],v[210];
int main(){
    scanf("%d%d",&N,&M);
    int a;
    for(int i=0;i<M;i++){
        scanf("%d",&a);
        if(!v[a])v[a]=i+1;
    }
    scanf("%d",&L);
    for(int i=0;i<L;i++){
        scanf("%d",&a);
        if(v[a])
        for(int j=M;j>=v[a];j--){
            for(int k=v[a];k>=0;k--)
            dp[j]=max(dp[j],dp[k]+1);
        }
    }
    printf("%d\n",dp[M]);
    return 0;
}


阅读更多
换一批

没有更多推荐了,返回首页