#include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
string s;
cin>>s;
set<int> pos;
int n = s.size();
for(int i=0;i<n;i++){
if(s[i] == 'a') pos.insert(i);
}
long long res=0;
while(pos.size() >= 2){
int a = *pos.begin();
pos.erase(pos.begin());
int b = *prev(pos.end());
pos.erase(prev(pos.end()));
b = n-1-b;
res += abs(a-b);
}
if(pos.size() == 1){
if(n%2){
int a = *pos.begin();
res += abs(a-n/2);
}
else res = -1;
}
cout<<res<<endl;
}
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 | #include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); string s; cin>>s; set<int> pos; int n = s.size(); for(int i=0;i<n;i++){ if(s[i] == 'a') pos.insert(i); } long long res=0; while(pos.size() >= 2){ int a = *pos.begin(); pos.erase(pos.begin()); int b = *prev(pos.end()); pos.erase(prev(pos.end())); b = n-1-b; res += abs(a-b); } if(pos.size() == 1){ if(n%2){ int a = *pos.begin(); res += abs(a-n/2); } else res = -1; } cout<<res<<endl; } |
English