#include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #include <set> #include <chrono> using namespace std; long long transpositionNumber(string word) { long long countA = std::count(word.begin(), word.end(), 'a'); long long countB = std::count(word.begin(), word.end(), 'b'); if (countA % 2 == 1 && countB % 2 == 1) return -1; int low = 0; int high = word.size() - 1; long long result = 0; std::size_t firstA = word.find('a'); std::size_t firstB = word.find('b'); while (low + 1 < high) { if (word[low] != word[high]) { if (countA == 1 || countB == 1) { long long mid = (low + high) / 2; result += (mid - low); return result; } if (word[low] == 'a') { result += ((long long)firstB - low); word[low] = 'b'; word[firstB] = 'a'; firstB = word.find('b', firstB); firstA = low + 1; } else { result += ((long long)firstA - low); word[low] = 'a'; word[firstA] = 'b'; firstA = word.find('a', firstA); firstB = low + 1; } } if (word[low] == 'a') { countA -= 2; if (firstA == low) firstA = word.find('a', low+1); } else { countB -= 2; if (firstB == low) firstB = word.find('b', low + 1); } ++low; --high; } return result; } int main() { ios::sync_with_stdio(false); string word; std::cin >> word; std::cout << transpositionNumber(word); };
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 | #include <iostream> #include <vector> #include <algorithm> #include <string> #include <map> #include <set> #include <chrono> using namespace std; long long transpositionNumber(string word) { long long countA = std::count(word.begin(), word.end(), 'a'); long long countB = std::count(word.begin(), word.end(), 'b'); if (countA % 2 == 1 && countB % 2 == 1) return -1; int low = 0; int high = word.size() - 1; long long result = 0; std::size_t firstA = word.find('a'); std::size_t firstB = word.find('b'); while (low + 1 < high) { if (word[low] != word[high]) { if (countA == 1 || countB == 1) { long long mid = (low + high) / 2; result += (mid - low); return result; } if (word[low] == 'a') { result += ((long long)firstB - low); word[low] = 'b'; word[firstB] = 'a'; firstB = word.find('b', firstB); firstA = low + 1; } else { result += ((long long)firstA - low); word[low] = 'a'; word[firstA] = 'b'; firstA = word.find('a', firstA); firstB = low + 1; } } if (word[low] == 'a') { countA -= 2; if (firstA == low) firstA = word.find('a', low+1); } else { countB -= 2; if (firstB == low) firstB = word.find('b', low + 1); } ++low; --high; } return result; } int main() { ios::sync_with_stdio(false); string word; std::cin >> word; std::cout << transpositionNumber(word); }; |