#include <bits/stdc++.h> #define dbg(x) " [" << #x << ": " << (x) << "] " using namespace std; template<typename A, typename B> ostream& operator<<(ostream& out, const pair<A,B>& p) { return out << "(" << p.first << ", " << p.second << ")"; } template<typename T> ostream& operator<<(ostream& out, const vector<T>& c) { out << "{"; for(auto it = c.begin(); it != c.end(); it++) { if(it != c.begin()) out << ", "; out << *it; } return out << "}"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); string s; cin >> s; int n = s.length(); vector<set<int>> st(2); for(int i = 0; i < n; i++) { st[s[i] - 'a'].insert(i); } if((st[0].size() & 1) && (st[1].size() & 1)) { cout << -1 << endl; return 0; } long long ans = 0; for(int i = 0; i < n / 2; i++) { st[s[i] - 'a'].erase(i); st[s[n - 1 - i] - 'a'].erase(n - 1 - i); if(s[i] == s[n - 1 - i]) continue; int first = n - 1 - i; if(st[1 ^ (s[i] - 'a')].size()) first = *st[1 ^ (s[i] - 'a')].begin(); int last = i; if(st[1 ^ (s[n - 1 - i] - 'a')].size()) last = *prev(st[1 ^ (s[n - 1 - i] - 'a')].end()); if(first - i < n - 1 - i - last) { ans += first - i; st[s[first] - 'a'].erase(first); st[s[i] - 'a'].insert(first); swap(s[i], s[first]); } else { ans += n - 1 - i - last; st[s[last] - 'a'].erase(last); st[s[n - 1 - i] - 'a'].insert(last); swap(s[n - 1 - i], s[last]); } } cout << ans << endl; 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 | #include <bits/stdc++.h> #define dbg(x) " [" << #x << ": " << (x) << "] " using namespace std; template<typename A, typename B> ostream& operator<<(ostream& out, const pair<A,B>& p) { return out << "(" << p.first << ", " << p.second << ")"; } template<typename T> ostream& operator<<(ostream& out, const vector<T>& c) { out << "{"; for(auto it = c.begin(); it != c.end(); it++) { if(it != c.begin()) out << ", "; out << *it; } return out << "}"; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); string s; cin >> s; int n = s.length(); vector<set<int>> st(2); for(int i = 0; i < n; i++) { st[s[i] - 'a'].insert(i); } if((st[0].size() & 1) && (st[1].size() & 1)) { cout << -1 << endl; return 0; } long long ans = 0; for(int i = 0; i < n / 2; i++) { st[s[i] - 'a'].erase(i); st[s[n - 1 - i] - 'a'].erase(n - 1 - i); if(s[i] == s[n - 1 - i]) continue; int first = n - 1 - i; if(st[1 ^ (s[i] - 'a')].size()) first = *st[1 ^ (s[i] - 'a')].begin(); int last = i; if(st[1 ^ (s[n - 1 - i] - 'a')].size()) last = *prev(st[1 ^ (s[n - 1 - i] - 'a')].end()); if(first - i < n - 1 - i - last) { ans += first - i; st[s[first] - 'a'].erase(first); st[s[i] - 'a'].insert(first); swap(s[i], s[first]); } else { ans += n - 1 - i - last; st[s[last] - 'a'].erase(last); st[s[n - 1 - i] - 'a'].insert(last); swap(s[n - 1 - i], s[last]); } } cout << ans << endl; return 0; } |