#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define endl "\n"
#define pii pair<ll,ll>
#define pb push_back
#define vi vector<ll>
#define pque priority_queue
#define pqueg priority_queue<ll,vector<ll>,greater<ll>>
#define que queue<ll>
#define FOR(m,i,n) for(int i=(m); i<=(n); i++)
#define FORM(m,i,n) for(int i=(m); i>=(n); i--)
#define all(v) sort(v.begin(),v.end())
ll n;
string s;
char c[4] = {'R', 'G', 'Y'};
map<string,bool> vis[405];
map<string,ll> memo[405];
ll dp(ll idx, string a) {
// cout << idx << " " << a << endl;
if(idx == n+1) {
FOR(2,i,n) {
if(a[i-1] == a[i]) return 1e9;
}
return 0;
}
if(!vis[idx][a]) {
vis[idx][a] = true;
memo[idx][a] = 1e9;
if(a[idx] != a[idx-1]) memo[idx][a] = dp(idx+1,a);
FOR(0,l,2) {
// if(idx == 1) {
// cout << "warna " << c[l] << endl;
// }
if(a[idx] != c[l] && a[idx-1] != c[l]) {
FOR(idx+1,i,n) {
if(s[i] == c[l]) {
string s1 = a;
FORM(i,j,idx+1) {
swap(s1[j],s1[j-1]);
}
// cout << "DEBUG " << temp << endl;
// cout << "string " << s1 << endl;
memo[idx][a] = min(memo[idx][a],dp(idx+1,s1)+(i-idx));
break;
}
}
}
}
}
// cout << "memo " << memo[idx][a] << endl;
return memo[idx][a];
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> s;
s = '!' + s;
if(dp(1,s) == 1e9) cout << -1 << endl;
else cout << dp(1,s) << endl;
}
/*
5
GGGRR
7
GGRRGRR
*/
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
0 ms |
340 KB |
Output is correct |
3 |
Correct |
1 ms |
340 KB |
Output is correct |
4 |
Correct |
1 ms |
340 KB |
Output is correct |
5 |
Incorrect |
2 ms |
852 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
0 ms |
340 KB |
Output is correct |
3 |
Correct |
1 ms |
340 KB |
Output is correct |
4 |
Correct |
1 ms |
340 KB |
Output is correct |
5 |
Incorrect |
2 ms |
852 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
340 KB |
Output is correct |
2 |
Incorrect |
1 ms |
852 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
340 KB |
Output is correct |
2 |
Correct |
0 ms |
340 KB |
Output is correct |
3 |
Correct |
1 ms |
340 KB |
Output is correct |
4 |
Correct |
1 ms |
340 KB |
Output is correct |
5 |
Incorrect |
2 ms |
852 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |