#include <bits/stdc++.h> int main(void) { std::string input; std::cin >> input; int a, b; long long output = 0; a = std::count(input.begin(), input.end(), 'a'); b = std::count(input.begin(), input.end(), 'b'); if (a % 2 == 1 && b % 2 == 1) output = -1; else { int n = input.length(); std::vector<int> a_pos; for (int i = 0; i < n; ++i) if (input[i] == 'a') a_pos.push_back(i); for (int i = 0; i < a_pos.size() / 2; ++i) output += abs(n - a_pos[i] - a_pos[a_pos.size() - i - 1] - 1); if (a_pos.size() % 2 == 1) output += abs(a_pos[a_pos.size() / 2] - n / 2); } std::cout << output; 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 | #include <bits/stdc++.h> int main(void) { std::string input; std::cin >> input; int a, b; long long output = 0; a = std::count(input.begin(), input.end(), 'a'); b = std::count(input.begin(), input.end(), 'b'); if (a % 2 == 1 && b % 2 == 1) output = -1; else { int n = input.length(); std::vector<int> a_pos; for (int i = 0; i < n; ++i) if (input[i] == 'a') a_pos.push_back(i); for (int i = 0; i < a_pos.size() / 2; ++i) output += abs(n - a_pos[i] - a_pos[a_pos.size() - i - 1] - 1); if (a_pos.size() % 2 == 1) output += abs(a_pos[a_pos.size() / 2] - n / 2); } std::cout << output; return 0; } |