Salvens

G

Aug 3rd, 2023
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <vector>
  4. #include <array>
  5. #include <set>
  6.  
  7. using namespace std;
  8.  
  9. //#define int long long
  10.  
  11. const long long INF = 1e9 + 7;
  12. const int MAXN = 105;
  13. const int N = 1e5 + 10;
  14. const int MOD = 1e9 + 7;
  15.  
  16. int dp[MAXN][MAXN][MAXN];
  17.  
  18. void init_dp() {
  19.     for (int i = 0; i < MAXN; ++i) {
  20.         for (int j = 0; j < MAXN; ++j) {
  21.             for (int k = 0; k < MAXN; ++k) {
  22.                 dp[i][j][k] = INF;
  23.             }
  24.         }
  25.     }
  26. }
  27.  
  28. signed main() {
  29.     ios_base::sync_with_stdio(false);
  30.     cin.tie(nullptr);
  31.     cout.tie(nullptr);
  32.     int n, m;
  33.     cin >> n >> m;
  34.     vector<int> a(n);
  35.     for (int i = 0; i < n; ++i) {
  36.         cin >> a[i];
  37.     }
  38.     init_dp();
  39.     for (int i = 0; i < n; ++i) {
  40.         for (int j = 1; j <= m; ++j) {
  41.             dp[i][i][j] = (a[i] == j ? 0 : 1);
  42.         }
  43.     }
  44.     for (int len = 2; len <= n; ++len) {
  45.         for (int l = 0; l + len - 1 < n; ++l) {
  46.             int r = l + len - 1;
  47.             for (int col = 1; col <= m; ++col) {
  48.                 for (int mid = l; mid < r; ++mid) {
  49.                     dp[l][r][col] = min(dp[l][r][col], dp[l][mid][col] + dp[mid + 1][r][col]);
  50.                 }
  51.                 if (a[l] == a[r]) {
  52.                     if (len > 2) {
  53.                         dp[l][r][col] = min(dp[l][r][col], dp[l + 1][r - 1][a[l]] + (a[l] == col ? 0 : 1));
  54.                     } else {
  55.                         dp[l][r][col] = min(dp[l][r][col], (a[l] == col ? 0 : 1));
  56.                     }
  57.                 }
  58.             }
  59.         }
  60.     }
  61.     int ans = INF;
  62.     for (int col = 1; col <= m; ++col) {
  63.         ans = min(ans, dp[0][n - 1][col]);
  64.     }
  65.     cout << ans << '\n';
  66. }
Advertisement
Add Comment
Please, Sign In to add comment