//Dawid Lebryk #include <iostream> #include <queue> using namespace std; typedef long long ll; const int MAXN = 200000; int tab[MAXN + 1]; deque<int> inda, indb; void add(int a) { for (int i = a; i > 0; i -= (i & -i)) { tab[i]++; } } int sum(int a) { int s = 0; for (int i = a; i <= MAXN; i += (i & -i)) { s += tab[i]; } return s; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); string s; cin >> s; ll n = s.size(); for (int i = 1; i <= n; i++) { if (s[i - 1] == 'a') { inda.push_back(i); } else { indb.push_back(i); } } if (inda.size() % 2 == 1 && indb.size() % 2 == 1) { cout << -1; return 0; } ll w = 0; for (int i = 1; i <= n; i++) { if (s[i - 1] == 'a') { if (!inda.empty()) { ll p = n - inda.back() - sum(inda.back()); add(inda.back()); if (inda.size() > 1) inda.pop_back(); else p /= 2; inda.pop_front(); w += p; } } else { if (!indb.empty()) { ll p = n - indb.back() - sum(indb.back()); add(indb.back()); if (indb.size() > 1) indb.pop_back(); else p /= 2; indb.pop_front(); w += p; } } } cout << w; 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 74 75 76 77 78 79 80 81 82 83 | //Dawid Lebryk #include <iostream> #include <queue> using namespace std; typedef long long ll; const int MAXN = 200000; int tab[MAXN + 1]; deque<int> inda, indb; void add(int a) { for (int i = a; i > 0; i -= (i & -i)) { tab[i]++; } } int sum(int a) { int s = 0; for (int i = a; i <= MAXN; i += (i & -i)) { s += tab[i]; } return s; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); string s; cin >> s; ll n = s.size(); for (int i = 1; i <= n; i++) { if (s[i - 1] == 'a') { inda.push_back(i); } else { indb.push_back(i); } } if (inda.size() % 2 == 1 && indb.size() % 2 == 1) { cout << -1; return 0; } ll w = 0; for (int i = 1; i <= n; i++) { if (s[i - 1] == 'a') { if (!inda.empty()) { ll p = n - inda.back() - sum(inda.back()); add(inda.back()); if (inda.size() > 1) inda.pop_back(); else p /= 2; inda.pop_front(); w += p; } } else { if (!indb.empty()) { ll p = n - indb.back() - sum(indb.back()); add(indb.back()); if (indb.size() > 1) indb.pop_back(); else p /= 2; indb.pop_front(); w += p; } } } cout << w; return 0; } |