#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define MAXN 1000
#define INF 987654321
int cache[MAXN];
int map[MAXN];
int N;
int dp(int pos) {
if (pos == N - 1) return 0;
int& ret = cache[pos];
if (ret != -1) return ret;
ret = INF;
for (int i = pos + 1; i < N; i++) {
if ((map[pos] + 1) % 3 == map[i]) {
ret = min(ret, dp(i) + (i - pos) * (i - pos));
}
}
return ret;
}
int main() {
scanf("%d", &N);
memset(cache, -1, sizeof(cache));
for (int i = 0; i < N; i++) {
char tmp;
scanf(" %1c", &tmp);
if (tmp == 'B') map[i] = 0;
else if (tmp == 'O') map[i] = 1;
else map[i] = 2;
}
int ans = dp(0);
ans = (ans == INF) ? -1 : ans;
printf("%d", ans);
return 0;
}