Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <vector>
- #include <array>
- #include <set>
- using namespace std;
- //#define int long long
- const long long INF = 1e9 + 7;
- const int MAXN = 105;
- const int N = 1e5 + 10;
- const int MOD = 1e9 + 7;
- int dp[MAXN][MAXN][MAXN];
- void init_dp() {
- for (int i = 0; i < MAXN; ++i) {
- for (int j = 0; j < MAXN; ++j) {
- for (int k = 0; k < MAXN; ++k) {
- dp[i][j][k] = INF;
- }
- }
- }
- }
- signed main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int n, m;
- cin >> n >> m;
- vector<int> a(n);
- for (int i = 0; i < n; ++i) {
- cin >> a[i];
- }
- init_dp();
- for (int i = 0; i < n; ++i) {
- for (int j = 1; j <= m; ++j) {
- dp[i][i][j] = (a[i] == j ? 0 : 1);
- }
- }
- for (int len = 2; len <= n; ++len) {
- for (int l = 0; l + len - 1 < n; ++l) {
- int r = l + len - 1;
- for (int col = 1; col <= m; ++col) {
- for (int mid = l; mid < r; ++mid) {
- dp[l][r][col] = min(dp[l][r][col], dp[l][mid][col] + dp[mid + 1][r][col]);
- }
- if (a[l] == a[r]) {
- if (len > 2) {
- dp[l][r][col] = min(dp[l][r][col], dp[l + 1][r - 1][a[l]] + (a[l] == col ? 0 : 1));
- } else {
- dp[l][r][col] = min(dp[l][r][col], (a[l] == col ? 0 : 1));
- }
- }
- }
- }
- }
- int ans = INF;
- for (int col = 1; col <= m; ++col) {
- ans = min(ans, dp[0][n - 1][col]);
- }
- cout << ans << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment