#include <iostream> #include <vector> using namespace std; typedef long long ll; constexpr int mSize = 2e5 + 5; int main() { ios_base::sync_with_stdio(NULL); cin.tie(NULL); cout.tie(NULL); int ileA, ileB; string a; cin >> a; ileA = ileB = 0; for (char x : a) (x == 'a') ? ++ileA : ++ileB; if (ileA % 2 && ileB % 2) { cout << "-1\n"; return 0; } int r, iter; r = (int)a.size() - 1; ll result = 0; for (int i = 0; i < a.size()/2; i++) { iter = r; while (a[i] != a[iter]) --iter; if (i != iter) { result += r - iter; a[iter] = a[r]; } else { result += a.size() / 2 - i; ++r; } --r; } 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 53 54 55 56 57 | #include <iostream> #include <vector> using namespace std; typedef long long ll; constexpr int mSize = 2e5 + 5; int main() { ios_base::sync_with_stdio(NULL); cin.tie(NULL); cout.tie(NULL); int ileA, ileB; string a; cin >> a; ileA = ileB = 0; for (char x : a) (x == 'a') ? ++ileA : ++ileB; if (ileA % 2 && ileB % 2) { cout << "-1\n"; return 0; } int r, iter; r = (int)a.size() - 1; ll result = 0; for (int i = 0; i < a.size()/2; i++) { iter = r; while (a[i] != a[iter]) --iter; if (i != iter) { result += r - iter; a[iter] = a[r]; } else { result += a.size() / 2 - i; ++r; } --r; } cout << result << '\n'; return 0; } |