#include <bits/stdc++.h> using namespace std; void testcase() { int n; cin >> n; string s; cin >> s; priority_queue <int> Q1, Q2; int ones = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { ones++; continue; } int j = i; while (j+1 < n && s[j+1] == '0') j++; if (i == 0 || j == n-1) { Q1.push(j-i+1); } else { Q2.push(j-i+1); } i = j; } int t = 0, saved = 0; bool anything_saved; for (anything_saved = true ; anything_saved; t++) { anything_saved = false; if (!Q1.empty() && !Q2.empty()) { int r1 = Q1.top(), r2 = Q2.top(); if (r1-t > 0 && r2-2*t > 0) { int cl1 = r1-t, cl2 = r2-2*t; int lost1 = min(3, cl2); int lost2 = min(1, cl2-1) + min(2, cl1); if (lost1 <= lost2) { anything_saved = true; saved += cl1; Q1.pop(); continue; } else { anything_saved = true; saved++; Q2.pop(); Q1.push(cl2-1); continue; } } } if (!Q2.empty()) { int r = Q2.top(); if (r-2*t > 0) { anything_saved = true; saved++; Q2.pop(); Q1.push(r-2*t-1); continue; } } if (!Q1.empty()) { int r = Q1.top(); if (r - t > 0) { anything_saved = true; saved += r-t; Q1.pop(); continue; } } } cout << n-saved <<endl; } int main() { ios_base::sync_with_stdio(false); int T; cin >> T; for (int t = 0; t < T; t++) { testcase(); } 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | #include <bits/stdc++.h> using namespace std; void testcase() { int n; cin >> n; string s; cin >> s; priority_queue <int> Q1, Q2; int ones = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') { ones++; continue; } int j = i; while (j+1 < n && s[j+1] == '0') j++; if (i == 0 || j == n-1) { Q1.push(j-i+1); } else { Q2.push(j-i+1); } i = j; } int t = 0, saved = 0; bool anything_saved; for (anything_saved = true ; anything_saved; t++) { anything_saved = false; if (!Q1.empty() && !Q2.empty()) { int r1 = Q1.top(), r2 = Q2.top(); if (r1-t > 0 && r2-2*t > 0) { int cl1 = r1-t, cl2 = r2-2*t; int lost1 = min(3, cl2); int lost2 = min(1, cl2-1) + min(2, cl1); if (lost1 <= lost2) { anything_saved = true; saved += cl1; Q1.pop(); continue; } else { anything_saved = true; saved++; Q2.pop(); Q1.push(cl2-1); continue; } } } if (!Q2.empty()) { int r = Q2.top(); if (r-2*t > 0) { anything_saved = true; saved++; Q2.pop(); Q1.push(r-2*t-1); continue; } } if (!Q1.empty()) { int r = Q1.top(); if (r - t > 0) { anything_saved = true; saved += r-t; Q1.pop(); continue; } } } cout << n-saved <<endl; } int main() { ios_base::sync_with_stdio(false); int T; cin >> T; for (int t = 0; t < T; t++) { testcase(); } return 0; } |