이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define ll long long
#define ar array
#define db double
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define rint(l, r) uniform_int_distribution<int>(l, r)(rng)
template<typename T> bool ckmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template<typename T> bool ckmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }
const int INF = 1e9;
int pref[3][3][401][401];
void test_case() {
int n; string s;
cin >> n >> s;
vector<int> a(n);
for (int i = 0; i < n; i++) {
a[i] = (s[i] == 'R' ? 0 : s[i] == 'G' ? 1 : 2);
}
ar<int, 3> on{};
int where[3][n+1];
memset(where, -1, sizeof(where));
for (int i = 0; i < n; i++) {
where[a[i]][on[a[i]]++] = i;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// those pos[j] > pos[i]
for (int k = 0; k < on[i]; k++) {
for (int l = 0; l <= on[j]; l++) {
for (int r = 0; r < l; r++) {
pref[i][j][k][l] += where[j][r] > where[i][k];
}
}
}
}
}
int dp[on[0]+1][on[1]+1][on[2]+1][3];
fill(&dp[0][0][0][0], &dp[0][0][0][0] + 3*(on[0]+1)*(on[1]+1)*(on[2]+1), INF);
memset(dp[0][0][0], 0, sizeof(dp[0][0][0]));
for (int s = 0; s < n; s++) {
for (int i = 0; i <= min(on[0], s); i++) {
for (int j = 0; j <= on[1] && i+j <= s; j++) {
if (s-i-j > on[2]) continue;
ar<int, 3> cur{i, j, s-i-j};
for (int k = 0; k < 3; k++) {
if (dp[i][j][s-i-j][k] == INF) continue;
for (int nw = 0; nw < 3; nw++) if (nw != k) {
int pos = where[nw][cur[nw]];
if (~pos) {
int cnt2 = 0;
for (int z = 0; z < 3; z++) if (z != nw) {
cnt2 += pref[nw][z][cur[nw]][cur[z]];
}
ckmin(dp[i+(nw==0)][j+(nw==1)][s-i-j+(nw==2)][nw], dp[i][j][s-i-j][k] + cnt2);
}
}
}
}
}
}
int ans = INF;
for (int k = 0; k < 3; k++) {
ckmin(ans, dp[on[0]][on[1]][on[2]][k]);
}
cout << (ans == INF ? -1 : ans) << '\n';
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int t = 1;
// cin >> t;
while (t--) test_case();
}
# | 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... |