题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805437411475456
题目分析:
本题要求从一个序列中得到满足给定次序子序列的最大长度。
本题属于动态规划问题,dp[i]表示到位置i时,满足条件的子序列(以i结尾)最大长度。ans表示当前循环(到i为止),满足条件的子序列最大长度。
参考代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int nmax = 210;
const int inf = 999999;
vector<int> color;
int mark[nmax], pos = 1; //记录喜欢的颜色顺序
int main()
{
memset(mark, 0, sizeof(mark));
int n1, n2, n3;
cin >> n1 >> n2;
for (int i = 0; i < n2; ++i) {
int tmp;
cin >> tmp;
mark[tmp] = pos++;
}
cin >> n3;
for (int i = 0; i < n3; ++i) {
int tmp;
cin >> tmp;
if (mark[tmp] != 0) {
color.push_back(tmp);
}
}
int dp[10005],ans = 0; //d[i]表示到位置i截止,喜欢颜色构成色条的最大长度
for (int i = 0; i < color.size(); ++i) {
//定义边界
dp[i] = 1;
for (int j = 0; j < i; ++j) {
if (mark[color[i]] >= mark[color[j]] && dp[i] < dp[j] + 1)
dp[i] = dp[j] + 1;
}
ans = max(ans, dp[i]);
}
cout << ans;
return 0;
}