#include <iostream> using namespace std; string a; int ile; int sum; int main() { std::ios_base::sync_with_stdio(0); cin>>a; for(int i=0;i<a.size();i++) { if(a[i]=='a')ile++; } if(a.size()%2==0&&ile%2==1) { cout<<-1; return 0; } int ii=0; int jj=a.size()-1; int i=ii; int j=jj; while(1) { while(i<jj&&a[i]!='b')i++; while(j>ii&&a[j]!='b')j--; if(i>j) { cout<<sum; return 0; } if(i==j) { sum+=abs((int)a.size()/2-i); cout<<sum; return 0; } else { sum+=abs(j-(jj-i)); i++; j--; } } 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 | #include <iostream> using namespace std; string a; int ile; int sum; int main() { std::ios_base::sync_with_stdio(0); cin>>a; for(int i=0;i<a.size();i++) { if(a[i]=='a')ile++; } if(a.size()%2==0&&ile%2==1) { cout<<-1; return 0; } int ii=0; int jj=a.size()-1; int i=ii; int j=jj; while(1) { while(i<jj&&a[i]!='b')i++; while(j>ii&&a[j]!='b')j--; if(i>j) { cout<<sum; return 0; } if(i==j) { sum+=abs((int)a.size()/2-i); cout<<sum; return 0; } else { sum+=abs(j-(jj-i)); i++; j--; } } return 0; } |