#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
string st;
cin >> st;
int cnt[3] {};
vector<int> id[3][3];
for(int i = 0; i < n; i++) {
int x = -1;
if(st[i] == 'R') {
cnt[0]++;
x = 0;
}
if(st[i] == 'G') {
cnt[1]++;
x = 1;
}
if(st[i] == 'Y') {
cnt[2]++;
x = 2;
}
id[x][0].push_back(cnt[0]);
id[x][1].push_back(cnt[1]);
id[x][2].push_back(cnt[2]);
}
vector<vector<vector<vector<ll>>>> dp(cnt[0] + 1, vector<vector<vector<ll>>> (cnt[1] + 1, vector<vector<ll>> (cnt[2] + 1, vector<ll> (3, 1e18))));
dp[0][0][0][0] = dp[0][0][0][1] = dp[0][0][0][2] = 0;
for(int i = 0; i <= cnt[0]; i++) {
for(int j = 0; j <= cnt[1]; j++) {
for(int k = 0; k <= cnt[2]; k++) {
for(int l = 0; l < 3; l++) {
if(l != 0) {
if(i + 1 <= cnt[0]) {
dp[i + 1][j][k][0] = min(dp[i + 1][j][k][0], dp[i][j][k][l] + max(0, j - id[0][1][i]) + max(0, k - id[0][2][i]));
}
}
if(l != 1 && j + 1 <= cnt[1]) {
dp[i][j + 1][k][1] = min(dp[i][j + 1][k][1], dp[i][j][k][l] + max(0, i - id[1][0][j]) + max(0, k - id[1][2][j]));
}
if(l != 2 && k + 1 <= cnt[2]) {
dp[i][j][k + 1][2] = min(dp[i][j][k + 1][2], dp[i][j][k][l] + max(0, i - id[2][0][k]) + max(0, j - id[2][1][k]));
}
}
}
}
}
ll ans = min({dp[cnt[0]][cnt[1]][cnt[2]][0], dp[cnt[0]][cnt[1]][cnt[2]][1], dp[cnt[0]][cnt[1]][cnt[2]][2]});
cout << (ans == 1e17 ? -1 : ans) << '\n';
return 0;
}
# | 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... |