#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned int ui; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<long long> vll; const ll LINF = 1e18; const int INF = 1e9; ll count_moves(string &s, char c) { ll n_moves = 0; int left_i = 0; int right_i = s.size() - 1; while (left_i < right_i) { while (s[left_i] != c) { ++left_i; } while (s[right_i] != c) { --right_i; } // cerr << left_i << " " << right_i << '\n'; if (left_i == right_i) { // cnt(c) was odd n_moves += abs(left_i - (static_cast<int>(s.size() / 2))); break; } if (left_i >= right_i) { break; } n_moves += abs(left_i - (static_cast<int>(s.size()) - right_i - 1)); ++left_i; --right_i; } return n_moves; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int cnt[2] = {0, 0}; for (size_t i = 0; i < s.size(); ++i) { ++cnt[s[i] - 'a']; } // cerr << cnt[0] << ' ' << cnt[1] << '\n'; if (cnt[0] % 2 == 1 && cnt[1] % 2 == 1) { cout << "-1" << endl; return 0; } if (cnt[0] == 0 || cnt[1] == 0) { cout << "0" << endl; return 0; } // cerr << "a: " << count_moves(s, 'a') << '\n'; // cerr << "b: " << count_moves(s, 'b') << '\n'; cout << count_moves(s, 'a') << 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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned int ui; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<long long> vll; const ll LINF = 1e18; const int INF = 1e9; ll count_moves(string &s, char c) { ll n_moves = 0; int left_i = 0; int right_i = s.size() - 1; while (left_i < right_i) { while (s[left_i] != c) { ++left_i; } while (s[right_i] != c) { --right_i; } // cerr << left_i << " " << right_i << '\n'; if (left_i == right_i) { // cnt(c) was odd n_moves += abs(left_i - (static_cast<int>(s.size() / 2))); break; } if (left_i >= right_i) { break; } n_moves += abs(left_i - (static_cast<int>(s.size()) - right_i - 1)); ++left_i; --right_i; } return n_moves; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int cnt[2] = {0, 0}; for (size_t i = 0; i < s.size(); ++i) { ++cnt[s[i] - 'a']; } // cerr << cnt[0] << ' ' << cnt[1] << '\n'; if (cnt[0] % 2 == 1 && cnt[1] % 2 == 1) { cout << "-1" << endl; return 0; } if (cnt[0] == 0 || cnt[1] == 0) { cout << "0" << endl; return 0; } // cerr << "a: " << count_moves(s, 'a') << '\n'; // cerr << "b: " << count_moves(s, 'b') << '\n'; cout << count_moves(s, 'a') << endl; return 0; } |