This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#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 |
---|
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... |