#include <iostream> #include <string> using namespace std; int main() { string word; cin >> word; int aCount = 0; int bCount = 0; int wordSize = (int) word.size(); for (int i = 0; i < wordSize; i++) { if (word[i] == 'a') { aCount++; } else { bCount++; } } if ((wordSize % 2 == 0 && !(aCount % 2 == 0 && bCount % 2 == 0)) || (wordSize % 2 != 0 && !((aCount % 2 != 0 && bCount % 2 == 0) || (aCount % 2 == 0 && bCount % 2 != 0)))) { cout << "-1\n"; return 0; } int result = 0; int start = 0; int end = wordSize - 1; char letter = aCount % 2 == 0 ? 'a' : 'b'; while (start < end) { if (word[start] == letter && word[end] == letter) { result += abs(wordSize - (end + start) - 1); start++; end--; } else { if (word[start] != letter) start++; if (word[end] != letter) end--; } } 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 | #include <iostream> #include <string> using namespace std; int main() { string word; cin >> word; int aCount = 0; int bCount = 0; int wordSize = (int) word.size(); for (int i = 0; i < wordSize; i++) { if (word[i] == 'a') { aCount++; } else { bCount++; } } if ((wordSize % 2 == 0 && !(aCount % 2 == 0 && bCount % 2 == 0)) || (wordSize % 2 != 0 && !((aCount % 2 != 0 && bCount % 2 == 0) || (aCount % 2 == 0 && bCount % 2 != 0)))) { cout << "-1\n"; return 0; } int result = 0; int start = 0; int end = wordSize - 1; char letter = aCount % 2 == 0 ? 'a' : 'b'; while (start < end) { if (word[start] == letter && word[end] == letter) { result += abs(wordSize - (end + start) - 1); start++; end--; } else { if (word[start] != letter) start++; if (word[end] != letter) end--; } } cout << result << "\n"; return 0; } |