#include <iostream> #include <cstring> using namespace std; bool isBalanced(int count[], int length) { if (count[0] == length || count[1] == length || count[2] == length) { return true; } if (length % 2 == 0) { int half = length / 2; if ((count[0] == half && count[1] == half) || (count[1] == half && count[2] == half) || (count[0] == half && count[2] == half)) { return true; } } if (length % 3 == 0) { if (count[0] == count[1] && count[1] == count[2]) { return true; } } return false; } int main() { ios::sync_with_stdio(false); //string s = "aabbabcccba"; string s; cin >> s; int count[3] = { 0 }; long long int balancedCount = s.size() + s.size() - 1; for (int currentLength = 3; currentLength <= s.size(); currentLength++) { //if (currentLength % 2 != 0 && currentLength % 3 != 0) { // continue; //} memset(count, 0, sizeof(count)); for (int i = 0; i < currentLength; i++) { count[s[i] - 'a']++; } if (isBalanced(count, currentLength)) { balancedCount++; } for (int i = currentLength; i < s.size(); i++) { count[s[i] - 'a']++; count[s[i - currentLength] - 'a']--; if (isBalanced(count, currentLength)) { balancedCount++; } } } cout << balancedCount << endl; }
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 | #include <iostream> #include <cstring> using namespace std; bool isBalanced(int count[], int length) { if (count[0] == length || count[1] == length || count[2] == length) { return true; } if (length % 2 == 0) { int half = length / 2; if ((count[0] == half && count[1] == half) || (count[1] == half && count[2] == half) || (count[0] == half && count[2] == half)) { return true; } } if (length % 3 == 0) { if (count[0] == count[1] && count[1] == count[2]) { return true; } } return false; } int main() { ios::sync_with_stdio(false); //string s = "aabbabcccba"; string s; cin >> s; int count[3] = { 0 }; long long int balancedCount = s.size() + s.size() - 1; for (int currentLength = 3; currentLength <= s.size(); currentLength++) { //if (currentLength % 2 != 0 && currentLength % 3 != 0) { // continue; //} memset(count, 0, sizeof(count)); for (int i = 0; i < currentLength; i++) { count[s[i] - 'a']++; } if (isBalanced(count, currentLength)) { balancedCount++; } for (int i = currentLength; i < s.size(); i++) { count[s[i] - 'a']++; count[s[i - currentLength] - 'a']--; if (isBalanced(count, currentLength)) { balancedCount++; } } } cout << balancedCount << endl; } |