#include <bits/stdc++.h>
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
#define x first
#define y second
using namespace std;
using ll = long long;
#define int ll
void umin(int &a, int b) {
a = min(a, b);
}
void umax(int &a, int b) {
a = max(a, b);
}
const int N = 402;
const int INF = 1e18;
int n;
string str;
int a[N];
int pr[N];
int pg[N];
int py[N];
int wr[N];
int wg[N];
int wy[N];
int dp[N][N][N][3];
// R, G, Y, Last
signed main() {
#ifdef LC
assert(freopen("input.txt", "r", stdin));
#endif
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> str;
for (int i = 0; i < n; ++i) {
pr[i + 1] = pr[i];
pg[i + 1] = pg[i];
py[i + 1] = py[i];
if (str[i] == 'R') {
a[i] = 0;
wr[pr[i]] = i;
++pr[i + 1];
} else if (str[i] == 'G') {
a[i] = 1;
wg[pg[i]] = i;
++pg[i + 1];
} else {
assert(str[i] == 'Y');
a[i] = 2;
wy[py[i]] = i;
++py[i + 1];
}
}
fill_n(dp[0][0][0], 3 * N * N * N, INF);
dp[0][0][0][0] = 0;
dp[0][0][0][1] = 0;
dp[0][0][0][2] = 0;
for (int r = 0; r <= pr[n]; ++r) {
for (int g = 0; g <= pg[n]; ++g) {
for (int y = 0; y <= py[n]; ++y) {
for (int l = 0; l < 3; ++l) {
int v = dp[r][g][y][l];
if (l != 0 && r < pr[n]) {
int i = wr[r];
umin(dp[r + 1][g][y][0], v + abs(pg[i] - g) + abs(py[i] - y));
}
if (l != 1 && g < pg[n]) {
int i = wg[g];
umin(dp[r][g + 1][y][1], v + abs(pr[i] - r) + abs(py[i] - y));
}
if (l != 2 && y < py[n]) {
int i = wy[y];
umin(dp[r][g][y + 1][2], v + abs(pr[i] - r) + abs(pg[i] - g));
}
}
}
}
}
int r = pr[n], g = pg[n], y = py[n];
int ans = min(min(dp[r][g][y][0], dp[r][g][y][1]), dp[r][g][y][2]);
if (ans >= INF) {
cout << "-1\n";
return 0;
}
assert(ans % 2 == 0);
cout << ans / 2 << "\n";
return 0;
}
/**
RRGYY
->
RYRGY
**/
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
487 ms |
1048580 KB |
Execution killed with signal 9 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
487 ms |
1048580 KB |
Execution killed with signal 9 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
477 ms |
1048580 KB |
Execution killed with signal 9 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Runtime error |
487 ms |
1048580 KB |
Execution killed with signal 9 (could be triggered by violating memory limits) |
2 |
Halted |
0 ms |
0 KB |
- |