#include <iostream>
#include <deque>
#include <vector>
#include <cmath>
using namespace std;
deque<int>w;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
cin>>s;
int l=0,l2=0;
for(int i=1;i<=(int)s.length();i++){
if(s[i-1]=='a'){
w.push_back(i);
if(i<=(int)s.length()/2){
l++;
}
else{
l2++;
}
}
}
if((l+l2)%2==1&&(int)s.length()%2==0){
cout<<"-1";
}
else{
long long suma=0;
long long srodek=((int)s.length()/2)+1;
while(!w.empty()){
if((int)w.size()==1){
suma+=abs(w[0]-srodek);
w.pop_back();
}
else{
long long x=w.front();
long long x2=w.back();
w.pop_back();
w.pop_front();
if(l<=l2){
long long odbicie=(int)s.length()-x+1;
suma+=abs(x2-odbicie);
}
else{
long long odbicie=(int)s.length()-x2+1;
suma+=abs(x-odbicie);
}
}
}
cout<<suma;
}
return 0;
}
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 48 49 50 51 52 53 54 55 56 57 | #include <iostream> #include <deque> #include <vector> #include <cmath> using namespace std; deque<int>w; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; cin>>s; int l=0,l2=0; for(int i=1;i<=(int)s.length();i++){ if(s[i-1]=='a'){ w.push_back(i); if(i<=(int)s.length()/2){ l++; } else{ l2++; } } } if((l+l2)%2==1&&(int)s.length()%2==0){ cout<<"-1"; } else{ long long suma=0; long long srodek=((int)s.length()/2)+1; while(!w.empty()){ if((int)w.size()==1){ suma+=abs(w[0]-srodek); w.pop_back(); } else{ long long x=w.front(); long long x2=w.back(); w.pop_back(); w.pop_front(); if(l<=l2){ long long odbicie=(int)s.length()-x+1; suma+=abs(x2-odbicie); } else{ long long odbicie=(int)s.length()-x2+1; suma+=abs(x-odbicie); } } } cout<<suma; } return 0; } |
English