1045 Favorite Color Stripe(最长不下降子序列)
题意:按照题目给出的颜色序列找出原颜色序列中对应的子序列,给出的颜色序列不需要在子序列中全部出现。
解法:根据给出的序列对相应的颜色赋权值,就可以将颜色序列变成递增的权值序列,同样将原序列中出现的对应颜色变为相应权值,然后再找最长不下降子序列。(动态规划)
#include <iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXSIZE = 10010;
const int MAX = 0xffffff;
int N,L,M;
vector<int> vec;
map<int, int> m;
int dp[MAXSIZE];
int main()
{
cin >> N>>M;
int color,now_weigth;
for (int i = 1; i <= M; i++)
{
scanf("%d", &color);
m[color] = i;
}
cin >> L;
for (int i = 0; i < L; i++)
{
scanf("%d", &color);
if (m.count(color) != 0)
vec.push_back(m[color]);
}
int ans = -1;
for (int i = 0; i < vec.size(); i++)
{
//初始化当前位置
dp[i] = 1;
for (int j = 0; j < i; j++)
{
//如果当前位置的值大于之前某一个值,则当前位置的子序列长度为该位置的子序列长度+1
if (vec[i] >= vec[j] && dp[i] < dp[j] + 1)
dp[i] = dp[j] + 1;
}
//记录最大值
ans = max(ans, dp[i]);
}
cout << ans;
return 0;
}