#include <bits/stdc++.h> using namespace std; vector<int> V; int Ans(int t) { int res = 0; for (int i = 0; i < V.size(); i++) { auto v = V[i]; int after_time = v - 2 * t; int add = 0; if (after_time > 0) { add = max(1, after_time - 1); } res += add; if (add > 1) { t += 2; } else if (add == 1) { t++; } else { break; } } return res; } int Solve() { int length; string temp; cin >> length >> temp; V.clear(); V.reserve(length / 3); int left = 1; for (int i = 0; i < length; i++) { int right = temp[i] - '0'; if (left == 0 && right == 0) { V.back()++; } else if (left > right) { V.push_back(1); } left = right; } int L = 0; int R = 0; if (temp.back() == '0' && !V.empty()) { R = V.back(); V.pop_back(); } if (temp[0] == '0' && !V.empty()) { L = V[0]; swap(V[0], V.back()); V.pop_back(); } if (L < R) { swap(L, R); } if (V.empty()) { if (R == 0) { return length - L; } return length - L - R + 1; } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); int ans1 = (L > 0 && R > 0) ? L + R - 1 + Ans(2) : 0; int ans2 = (L > 0) ? L + Ans(1) : 0; int ans3 = Ans(0); return length - max(ans1, max(ans2, ans3)); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tests; cin >> tests; while (tests--) { cout << Solve() << "\n"; } }
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 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <bits/stdc++.h> using namespace std; vector<int> V; int Ans(int t) { int res = 0; for (int i = 0; i < V.size(); i++) { auto v = V[i]; int after_time = v - 2 * t; int add = 0; if (after_time > 0) { add = max(1, after_time - 1); } res += add; if (add > 1) { t += 2; } else if (add == 1) { t++; } else { break; } } return res; } int Solve() { int length; string temp; cin >> length >> temp; V.clear(); V.reserve(length / 3); int left = 1; for (int i = 0; i < length; i++) { int right = temp[i] - '0'; if (left == 0 && right == 0) { V.back()++; } else if (left > right) { V.push_back(1); } left = right; } int L = 0; int R = 0; if (temp.back() == '0' && !V.empty()) { R = V.back(); V.pop_back(); } if (temp[0] == '0' && !V.empty()) { L = V[0]; swap(V[0], V.back()); V.pop_back(); } if (L < R) { swap(L, R); } if (V.empty()) { if (R == 0) { return length - L; } return length - L - R + 1; } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); int ans1 = (L > 0 && R > 0) ? L + R - 1 + Ans(2) : 0; int ans2 = (L > 0) ? L + Ans(1) : 0; int ans3 = Ans(0); return length - max(ans1, max(ans2, ans3)); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tests; cin >> tests; while (tests--) { cout << Solve() << "\n"; } } |