// #pragma optimize ("g",on)
// #pragma GCC optimize ("inline")
// #pragma GCC optimize ("Ofast")
// #pragma GCC optimize ("unroll-loops")
// #pragma GCC optimize ("03")
#include <bits/stdc++.h>
#define pb push_back
#define SS ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr);
#define int long long
#define all(v) v.begin(),v.end()
using namespace std;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
const int N = 4e5 + 1, inf = 1e9 + 1, mod = 998244353;
void solve(){
int n;
cin >> n;
string s;
cin >> s;
s = '!' + s;
int a[n + 1] = {};
int cnt[3] = {}, pos[n + 1][3] = {}, pref[n + 1][3] = {};
for(int i = 1; i <= n; i++){
if(s[i] == 'R') a[i] = 0;
if(s[i] == 'G') a[i] = 1;
if(s[i] == 'Y') a[i] = 2;
cnt[a[i]]++;
pos[cnt[a[i]]][a[i]] = i;
for(int j = 0; j < 3; j++) pref[i][j] = cnt[j];
}
int dp[cnt[0] + 1][cnt[1] + 1][cnt[2] + 1][3] = {};
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 d = 0; d < 3; d++) dp[i][j][k][d] = inf;
}
}
}
dp[0][0][0][0] = dp[0][0][0][1] = dp[0][0][0][2] = 0;
for(int a = 0; a <= cnt[0]; a++){
for(int b = 0; b <= cnt[1]; b++){
for(int c = 0; c <= cnt[2]; c++){
for(int l = 0; l < 3; l++){
if(dp[a][b][c][l] == inf) continue;
if(l != 0 && a + 1 <= cnt[0]){
int p = pos[a + 1][0];
dp[a + 1][b][c][0] = min(dp[a + 1][b][c][0], dp[a][b][c][l] + max(0ll, pref[p][1] - b) + max(0ll, pref[p][2] - c));
}
if(l != 1 && b + 1 <= cnt[1]){
int p = pos[b + 1][1];
dp[a][b + 1][c][1] = min(dp[a][b + 1][c][1], dp[a][b][c][l] + max(0ll, pref[p][0] - a) + max(0ll, pref[p][2] - c));
}
if(l != 2 && c + 1 <= cnt[2]){
int p = pos[c + 1][2];
dp[a][b][c + 1][2] = min(dp[a][b][c + 1][2], dp[a][b][c][l] + max(0ll, pref[p][1] - b) + max(0ll, pref[p][0] - a));
}
}
}
}
}
int ans = inf;
for(int l = 0; l < 3; l++) ans = min(ans, dp[cnt[0]][cnt[1]][cnt[2]][l]);
cout << (ans >= inf ? -1 : ans);
}
signed main(){
SS
// freopen("trains.in", "r", stdin);
// freopen("trains.out", "w", stdout);
int t = 1;
// cin >> t;
while(t--){
solve();
}
}
| # | 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... |