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 N 70
using namespace std;
int n, v[N], pos[3][N], sz[3], inf = 2000000000;
int dp[N][N][N][4];
int solve(int i, int j, int z, int lst)
{
if(!i and !j and !z) return 0;
if(dp[i][j][z][lst] != -1) return dp[i][j][z][lst];
int A = inf, B = inf, C = inf;
if(i > 0 and lst != 0) A = solve(i - 1, j, z, 0) + abs(i + j + z - pos[0][i]);
if(j > 0 and lst != 1) B = solve(i, j - 1, z, 1) + abs(i + j + z - pos[1][j]);
if(z > 0 and lst != 2) C = solve(i, j, z - 1, 2) + abs(i + j + z - pos[2][z]);
return dp[i][j][z][lst] = min({A, B, C});
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
cin>>n;
for(int i = 1; i <= n; i++)
{
char c;
cin>>c;
if(c == 'R') v[i] = 0;
else if(c == 'Y') v[i] = 1;
else v[i] = 2;
++sz[v[i]];
pos[v[i]][sz[v[i]]] = i;
}
memset(dp, -1, sizeof dp);
int ans = solve(sz[0], sz[1], sz[2], 3)/2;
cout<<(2*ans >= inf ? -1 : ans)<<"\n";
}
# | 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... |