#include <iostream>
#include <cstdlib>
using namespace std;
inline bool is_palindrome_impossible(const string& str) {
unsigned long long a = 0, b = 0;
for(const char& i : str) {
if(i == 'a')
++a;
else
++b;
}
return ((a&1) && (b&1));
}
bool is_palindrome(string::const_iterator a, string::const_iterator b) {
while(a < --b)
if(*(a++) != *b)
return false;
return true;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
string str;
cin >> str;
if(is_palindrome_impossible(str)) {
cout << "-1";
return 0;
}
unsigned long long answer = 0;
auto iter_a = str.begin(), iter_b = --str.end();
while(iter_a < iter_b) {
auto tmp_a = iter_a, tmp_b = iter_b;
while(*tmp_a != *tmp_b)
--tmp_b;
if(tmp_a == tmp_b) {
swap(*tmp_b, *(tmp_b+1));
++answer;
} else {
swap(*tmp_b, *iter_b);
answer += iter_b - tmp_b;
++iter_a;
--iter_b;
}
}
cout << answer;
}
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 | #include <iostream> #include <cstdlib> using namespace std; inline bool is_palindrome_impossible(const string& str) { unsigned long long a = 0, b = 0; for(const char& i : str) { if(i == 'a') ++a; else ++b; } return ((a&1) && (b&1)); } bool is_palindrome(string::const_iterator a, string::const_iterator b) { while(a < --b) if(*(a++) != *b) return false; return true; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); string str; cin >> str; if(is_palindrome_impossible(str)) { cout << "-1"; return 0; } unsigned long long answer = 0; auto iter_a = str.begin(), iter_b = --str.end(); while(iter_a < iter_b) { auto tmp_a = iter_a, tmp_b = iter_b; while(*tmp_a != *tmp_b) --tmp_b; if(tmp_a == tmp_b) { swap(*tmp_b, *(tmp_b+1)); ++answer; } else { swap(*tmp_b, *iter_b); answer += iter_b - tmp_b; ++iter_a; --iter_b; } } cout << answer; } |
English