Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Jazz?

#include <bits/stdc++.h>
using namespace std;

void solve(string &str) {
    int n = str.length();

    vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
    // dp[i][j] is the minimum insertions to fix the subarray str[i...j]

    for (int i = n - 1; i >= 0; i--) {
        for (int j = i; j < n; j++) {
            // Length 1 substring. Only option is to append a character.
            if (i == j) {
                dp[i][j] = 1;
                continue;
            }
            // Consider the first character of this subarray, a[i].
            // You can either fix it by prefixing a[i].
            dp[i][j] = 1 + dp[i + 1][j];

            // Or, you can match it with some identical character.
            for (int k = i + 1; k <= j; k++) {
                if (str[i] == str[k]) {
                    dp[i][j] = min(dp[i][j], dp[i + 1][k - 1] + dp[k + 1][j]);
                }
            }
        }
    }
    cout << dp[0][n - 1] << endl;
}

int main() {
    string str;
    cin >> str;
    solve(str);
    return 0;
}