解法一:动态规划

按照喜欢的颜色的顺序定义优先级,剔除不喜欢的颜色后,剩下的数列就是一个最长不下降子序列问题。

  1. #include <bits/stdc++.h>
  2. const int MAX_N = 10001;
  3. const int MAX_M = 201;
  4. using namespace std;
  5. int dp[MAX_N];
  6. int colors[MAX_N];
  7. // priority[i] 表示颜色i的优先级
  8. int priority[MAX_M];
  9. int main() {
  10. ios::sync_with_stdio(false);
  11. cin.tie(0);
  12. int N, M, L, tmp;
  13. cin >> N;
  14. cin >> M;
  15. for (int i = 1; i <= M; ++i) {
  16. cin >> tmp;
  17. priority[tmp] = i;
  18. }
  19. cin >> L;
  20. int len = 0;
  21. for (int i = 0; i < L; ++i) {
  22. cin >> tmp;
  23. if (priority[tmp] != 0) {
  24. colors[len++] = priority[tmp];
  25. }
  26. }
  27. int ans;
  28. // 最长不下降子序列
  29. for (int i = 0; i < len; ++i) {
  30. dp[i] = 1;
  31. for (int j = 0; j < i; ++j) {
  32. if (colors[i] >= colors[j]) {
  33. dp[i] = max(dp[i], dp[j] + 1);
  34. }
  35. }
  36. ans = max(ans, dp[i]);
  37. }
  38. cout << ans << "\n";
  39. }