#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int count_a = 0, count_b = 0; for (auto c : s) { if (c == 'a') { count_a++; } else { count_b++; } } if (count_a % 2 == 1 && count_b % 2 == 1) { cout << -1 << '\n'; return 0; } if (count_a % 2 == 1) { for (auto &c : s) { if (c == 'a') { c = 'b'; } else { c = 'a'; } } } vector<int> positions_a; for (int i = 0; i < (int) s.size(); i++) { if (s[i] == 'a') { positions_a.emplace_back(i); } } long long result = 0; for (int left = 0, right = positions_a.size() - 1; left < right; left++, right--) { int left_position = positions_a[left], right_position = s.size() - 1 - positions_a[right]; result += abs(left_position - right_position); } cout << result << '\n'; 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 | #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int count_a = 0, count_b = 0; for (auto c : s) { if (c == 'a') { count_a++; } else { count_b++; } } if (count_a % 2 == 1 && count_b % 2 == 1) { cout << -1 << '\n'; return 0; } if (count_a % 2 == 1) { for (auto &c : s) { if (c == 'a') { c = 'b'; } else { c = 'a'; } } } vector<int> positions_a; for (int i = 0; i < (int) s.size(); i++) { if (s[i] == 'a') { positions_a.emplace_back(i); } } long long result = 0; for (int left = 0, right = positions_a.size() - 1; left < right; left++, right--) { int left_position = positions_a[left], right_position = s.size() - 1 - positions_a[right]; result += abs(left_position - right_position); } cout << result << '\n'; return 0; } |