219C - Color Stripe - CodeForces Solution


brute force dp greedy *1600

Please click on ads to support us..

C++ Code:

#pragma GCC optimize ("O3")

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>

#define ll long long
#define endl '\n'
#define fast ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define file freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
using namespace std;

const int OO = 0x3f3f3f3f, N = 5e5 + 5, mod = 1e9 + 7;

int n, k;
string s;
int dp[N][30];

int go(int idx, int lst) {
    if (idx == n) {
        return 0;
    }

    if (dp[idx][lst] != -1)
        return dp[idx][lst];

    int ans = 1e9;
    for (int i = 0; i < k; i++) {
        if (lst != i)
            ans = min(ans, go(idx + 1, i) + (s[idx] != (char) (i + 'A')));
    }
    return  dp[idx][lst] = ans;
}

void print(int idx, int lst) {
    if (idx == n) {
        return;
    }
    for (int i = 0; i < k; i++) {

        if (i != lst && go(idx + 1, i) + ((s[idx] - 'A') != i) == dp[idx][lst]) {
            cout << (char) (i + 'A');
            print(idx + 1, i);
            return;
        }

    }
}

int main() {
    fast;
    memset(dp, -1, sizeof dp);
    cin >> n >> k;
    cin >> s;
    cout << go(0, 29) << endl;
    print(0, 29);
}
			 							 		 			 					 	


Comments

Submit
0 Comments
More Questions

1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie
1605B - Reverse Sort
1607C - Minimum Extraction
1604B - XOR Specia-LIS-t
1606B - Update Files
1598B - Groups
1602B - Divine Array
1594B - Special Numbers
1614A - Divan and a Store
2085. Count Common Words With One Occurrence
2089. Find Target Indices After Sorting Array