#include <iostream> #include <vector> int64_t cost(int64_t l, int64_t r, int64_t m) { int64_t dist = std::max(std::abs(l-m), std::abs(r-m)); int64_t lpos = m-dist; int64_t rpos = m+dist; return std::abs(l-lpos) + std::abs(r-rpos); } int64_t cost2(int64_t l, int64_t r, int64_t m) { int64_t dist = std::max(std::abs(l-m), std::abs(r-m-1)); int64_t lpos = m-dist; int64_t rpos = m+1+dist; return std::abs(l-lpos) + std::abs(r-rpos); } int64_t solve(const std::string& p, char b) { std::vector<int64_t> pos; int64_t i = 0; for (char c : p) { if (c == b) { ++i; } else { pos.push_back(i); } } if (i%2 == 0) { int64_t sum = 0; int64_t l = 0, r = pos.size()-1; int64_t m = i/2; while (l < r) { sum += cost(pos[l], pos[r], m); ++l; --r; } if (l==r) sum += std::abs(pos[l]-m); return sum; } else { if (pos.size() %2 == 1) return -1; int64_t sum = 0; int64_t l = 0, r = pos.size()-1; int64_t m = i/2; while (l < r) { sum += cost2(pos[l], pos[r], m); ++l; --r; } return sum; } return 10*(i*pos.size()); } int main() { std::ios_base::sync_with_stdio(0); std::string p; std::cin >> p; std::cout << std::min(solve(p,'a'), solve(p,'b')) << std::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 | #include <iostream> #include <vector> int64_t cost(int64_t l, int64_t r, int64_t m) { int64_t dist = std::max(std::abs(l-m), std::abs(r-m)); int64_t lpos = m-dist; int64_t rpos = m+dist; return std::abs(l-lpos) + std::abs(r-rpos); } int64_t cost2(int64_t l, int64_t r, int64_t m) { int64_t dist = std::max(std::abs(l-m), std::abs(r-m-1)); int64_t lpos = m-dist; int64_t rpos = m+1+dist; return std::abs(l-lpos) + std::abs(r-rpos); } int64_t solve(const std::string& p, char b) { std::vector<int64_t> pos; int64_t i = 0; for (char c : p) { if (c == b) { ++i; } else { pos.push_back(i); } } if (i%2 == 0) { int64_t sum = 0; int64_t l = 0, r = pos.size()-1; int64_t m = i/2; while (l < r) { sum += cost(pos[l], pos[r], m); ++l; --r; } if (l==r) sum += std::abs(pos[l]-m); return sum; } else { if (pos.size() %2 == 1) return -1; int64_t sum = 0; int64_t l = 0, r = pos.size()-1; int64_t m = i/2; while (l < r) { sum += cost2(pos[l], pos[r], m); ++l; --r; } return sum; } return 10*(i*pos.size()); } int main() { std::ios_base::sync_with_stdio(0); std::string p; std::cin >> p; std::cout << std::min(solve(p,'a'), solve(p,'b')) << std::endl; return 0; } |