#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
string s;
ll a, b, wyn;
queue<int> kol[2];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>s;
for(char c:s)
{
a+=(c=='a');
b+=(c=='b');
}
if(a%2+b%2==2)
{
cout<<"-1\n";
return 0;
}
bool t=a%2;
for(int i=0; i<s.size(); ++i)
{
if(s.size()%2&&i==s.size()/2)continue;
if(t&&s[i]=='a')kol[i<s.size()/2].push(abs(i-(int)s.size()/2));
else if(!t&&s[i]=='b')kol[i<s.size()/2].push(i-s.size()/2);
}
if(kol[0].size()>kol[1].size())
{
wyn+=kol[0].front();
kol[0].pop();
}
else if(kol[1].size()>kol[0].size())
{
wyn+=kol[1].front();
kol[1].pop();
}
while(!kol[0].empty())
{
wyn+=abs(kol[0].front()-kol[1].front());
kol[0].pop();
kol[1].pop();
}
cout<<wyn<<"\n";
}
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 46 47 | #include <bits/stdc++.h> typedef long long ll; using namespace std; string s; ll a, b, wyn; queue<int> kol[2]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>s; for(char c:s) { a+=(c=='a'); b+=(c=='b'); } if(a%2+b%2==2) { cout<<"-1\n"; return 0; } bool t=a%2; for(int i=0; i<s.size(); ++i) { if(s.size()%2&&i==s.size()/2)continue; if(t&&s[i]=='a')kol[i<s.size()/2].push(abs(i-(int)s.size()/2)); else if(!t&&s[i]=='b')kol[i<s.size()/2].push(i-s.size()/2); } if(kol[0].size()>kol[1].size()) { wyn+=kol[0].front(); kol[0].pop(); } else if(kol[1].size()>kol[0].size()) { wyn+=kol[1].front(); kol[1].pop(); } while(!kol[0].empty()) { wyn+=abs(kol[0].front()-kol[1].front()); kol[0].pop(); kol[1].pop(); } cout<<wyn<<"\n"; } |
English