This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int main() {
int n;
string s;
cin >> n >> s;
int R = count(s.begin(), s.end(), 'R');
int G = count(s.begin(), s.end(), 'G');
int Y = count(s.begin(), s.end(), 'Y');
vector<int> red(n + 1), green(n + 1), yellow(n + 1);
for (int i = 0; i < n; i++) {
red[i + 1] = red[i] + (int)(s[i] == 'R');
green[i + 1] = green[i] + (int)(s[i] == 'G');
yellow[i + 1] = yellow[i] + (int)(s[i] == 'Y');
}
vector dp(R + 1, vector(G + 1, vector(Y + 1, vector<int>(4, INF))));
dp[R][G][Y][3] = 0;
for (int i = n; i > 0; i--) {
for (int r = 0; r <= R && r <= (i + 1) / 2; r++) {
for (int g = 0; g <= G && g <= (i + 1) / 2 && r + g <= i; g++) {
int y = i - r - g;
if (y > Y) {
continue;
}
for (int l = 0; l < 4; l++) {
int Rq = red[i - 1], Gq = green[i - 1], Yq = yellow[i - 1];
if (l != 0 && r > 0) {
dp[r - 1][g][y][0] = min(dp[r - 1][g][y][0], dp[r][g][y][l] + abs(Rq - (r - 1)) + abs(Gq - g) + abs(Yq - y));
}
if (l != 1 && g > 0) {
dp[r][g - 1][y][1] = min(dp[r][g - 1][y][1], dp[r][g][y][l] + abs(Rq - r) + abs(Gq - (g - 1)) + abs(Yq - y));
}
if (l != 2 && y > 0) {
dp[r][g][y - 1][2] = min(dp[r][g][y - 1][2], dp[r][g][y][l] + abs(Rq - r) + abs(Gq - g) + abs(Yq - (y - 1)));
}
}
}
}
}
int ans = min({dp[0][0][0][0], dp[0][0][0][1], dp[0][0][0][2]});
cout << (ans == INF ? -1 : ans / 2) << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |