#include <bits/stdc++.h>
#define int long long
signed main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n;
std::cin >> n;
std::string s;
std::cin >> s;
int ans = 0;
for (int i = 0; i < n; i++)
{
if (s[i] == 'A')
{
int ind = -1;
for (int j = i - 1; j >= 1; j--)
{
if (s[j] == 'B' && s[j - 1] == 'B')
{
ind = j;
}
}
for (int j = i - 1; j >= ind; j--)
{
ans++;
std::swap(s[j], s[j + 1]);
}
}
else
{
int ind = -1;
for (int j = i - 1; j >= 1; j--)
{
if (s[j] == 'A' && s[j - 1] == 'A')
{
ind = j;
}
}
for (int j = i - 1; j >= ind; j--)
{
ans++;
std::swap(s[j], s[j + 1]);
}
}
}
for (int i = n - 1; i >= 0; i--)
{
if (s[i] == 'A')
{
int ind = -1;
for (int j = i + 1; j < n - 1; j++)
{
if (s[j] == 'B' && s[j - 1] == 'B')
{
ind = j;
}
}
for (int j = i + 1; j <= ind; j++)
{
ans++;
std::swap(s[j], s[j - 1]);
}
}
else
{
int ind = -1;
for (int j = i + 1; j < n - 1; j++)
{
if (s[j] == 'A' && s[j - 1] == 'A')
{
ind = j;
}
}
for (int j = i + 1; j <= ind; j++)
{
ans++;
std::swap(s[j], s[j - 1]);
}
}
}
for (int i = 0; i < (int)s.size() - 1; i++)
{
if (s[i] == s[i + 1])
{
std::cout << -1;
return 0;
}
}
std::cout << ans;
}
# | 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... |