1045 Favorite Color Stripe
题目
思路
主要思路参考了算法笔记的思路,然后自己写出了代码,刚开始看这道题目也是一头雾水,不知道如何下手,只知道它属于是一类LIS类题目。题目给出了Eva喜欢的颜色顺序,而已知最长不下降子序列问题中寻找的子序列是一个非递减的序列,因此可以将Eva喜欢的颜色按顺序映射到一个递增序列,我通过使用数组进行映射,数组初始化值全为-1,例如,喜欢的颜色顺序为{2,3,1,5,6},则通过映射,将其映射为(1,2,3,4,5),而其他不在这5种颜色里的就为数组初始值-1,于是将问题转换为了LIS问题
代码
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 10010;
const int M = 210;
int HashTable[M];//对输入的颜色值进行映射
int A[maxn], dp[maxn];
int n;//颜色数
int main()
{
memset(HashTable, -1, sizeof(HashTable));//对数组初始化
scanf("%d", &n);
//输入喜欢的颜色数
int m;
scanf("%d", &m);
//颜色映射
for (int i = 1; i <= m; i++)
{
int tempM;
scanf("%d", &tempM);
HashTable[tempM] = i;//进行映射
}
//输入所有的颜色
int L;
int count = 0;
scanf("%d", &L);
for (int i = 1; i <= L; i++)
{
int tempL;
scanf("%d", &tempL);
//剔除掉不需要的颜色
if (HashTable[tempL]!=-1)
{
A[++count] = HashTable[tempL];
}
}
//调试用:输出A[i]
/*for (int i = 1; i <= count; i++)
{
printf("%d ", A[i]);
}
cout << endl;*/
//LIS求解
int ans = -1;
for (int i = 1; i <= count; i++)
{
dp[i] = 1;
for (int j = 1; j < i; j++)
{
if (A[i]>=A[j]&&dp[j]+1>dp[i])
{
dp[i] = dp[j] + 1;//长度增加
}
}
ans = max(ans, dp[i]);
}
printf("%d", ans);
return 0;
}
结果
![](https://i-blog.csdnimg.cn/blog_migrate/ddf374474fd5fe357416844f419a9410.png)