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>
#define ll long long
#define rep(a,b,c) for(ll a=b; a<c; a++)
#define repr(a,b,c) for(ll a=b-1; a>c-1; a--)
using namespace std;
int n;
string s, s2;
int mn=1e9;
void solve(int k, int r, int y, int g, int l){
if(y<0 || g<0 || r<0) return;
if(!l) s2[k-1]='R';
else if(l&1) s2[k-1]='Y';
else s2[k-1]='G';
if(k==n){
int sum=0;
string s3=s;
rep(i,0,n){
if(s2[i]==s3[i]) continue;
rep(j,i,n){
if(s3[j]==s2[i]){
repr(k,j,i) swap(s3[k+1],s3[k]);
sum+=(j-i);
break;
}
}
}
mn=min(mn,sum);
return;
}
if(!l) solve(k+1,r,y-1,g,1), solve(k+1,r,y,g-1,2);
else if(l&1) solve(k+1,r-1,y,g,0), solve(k+1,r,y,g-1,2);
else solve(k+1,r,y-1,g,1), solve(k+1,r-1,y,g,0);
}
int main(){
cin>>n>>s;
int r=0, g=0, y=0;
rep(i,0,n){
if(s[i]=='R') r++;
if(s[i]=='G') g++;
if(s[i]=='Y') y++;
}
s2=s;
solve(1,r-1,y,g,0);
solve(1,r,y-1,g,1);
solve(1,r,y,g-1,2);
if(n==1) mn=0;
if(mn<1e9) cout<<mn<<endl;
else cout<<-1<<endl;
}
# | 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... |