1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	string s; cin>>s;
	int a=0, b=0;
	for (auto i : s)
		if (i=='a') a++;
		else b++;
	if ((a&1) && (b&1))
	{
		cout<<"-1\n";
		return 0;
	}
	int n=s.length(), ind=0;
	long long ans=0;
	for (int i=0; i<n/2; i++)
	{
		if (a==1 || b==1)
		{
			if (a==1)
			{
				int j=i;
				while (s[j]!='a') j++;
				ans+=abs(n/2-j);
			}
			else
			{
				int j=i;
				while (s[j]!='b') j++;
				ans+=abs(n/2-j);
			}
			break;
		}
		if (s[i]==s[n-1-i]) continue;
		ind=max(ind, i);
		while (s[ind]!=s[n-1-i]) ind++;
		swap(s[i], s[ind]);
		ans+=(ind-i);
	}
	cout<<ans<<"\n";
	return 0;
}