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 FILE_IO
int N;
string s;
int solve1(string _s)
{
string s = _s;
int ans = 0;
for(int i = 1; i < N; i++)
{
if(s[i] != s[i - 1]) continue;
for(int j = i + 1; j < N; j++)
if(s[j] != s[i])
{
while(j > i)
{
swap(s[j], s[j - 1]);
j--;
ans++;
}
break;
}
}
for(int i = N - 1; i > 0; i--)
{
if(s[i] != s[i - 1]) continue;
for(int j = i - 2; j > 0; j--)
if(s[j] != s[i])
{
while(j < i - 1)
{
swap(s[j], s[j + 1]);
j++;
ans++;
}
break;
}
}
for(int i = 1; i < N; i++)
if(s[i] == s[i - 1]) return -1;
return ans;
}
int solve2(string _s)
{
string s = _s;
int ans = 0;
for(int i = N - 1; i > 0; i--)
{
if(s[i] != s[i - 1]) continue;
for(int j = i - 2; j > 0; j--)
if(s[j] != s[i])
{
while(j < i - 1)
{
swap(s[j], s[j + 1]);
j++;
ans++;
}
break;
}
}
for(int i = 1; i < N; i++)
{
if(s[i] != s[i - 1]) continue;
for(int j = i + 1; j < N; j++)
if(s[j] != s[i])
{
while(j > i)
{
swap(s[j], s[j - 1]);
j--;
ans++;
}
break;
}
}
for(int i = 1; i < N; i++)
if(s[i] == s[i - 1]) return -1;
return ans;
}
int main()
{
#ifdef FILE_IO
freopen("1.in", "r", stdin);
//freopen("1.out", "w", stdout);
#endif
cin >> N;
cin >> s;
int x = solve1(s);
int y = solve2(s);
cout << min(x, y) << '\n';
return 0;
}
# | 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... |