#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; vector<pair<int, int>> v; int l = 0; for (int i = 0; i < n; i++) { if (s[i] == '0') l++; else { v.push_back({l, 0}); l = 0; } } v.push_back({l, 0}); if (v.size() == 1) { cout << 0 << '\n'; continue; } v[0].first *= 2; v[0].second = 1; v.back().first *= 2; v.back().second = 1; sort(v.begin(), v.end(), [](pair<int, int>a, pair<int, int> b) { if (a.first != b.first) return a.first > b.first; return a.second > b.second; }); int r = 0, ans = 0; for (int i = 0; i < v.size(); i++) { if (v[i].second == 1) { ans += max(0, v[i].first/2-r); r++; } else if (v[i].first > 2*r) { ans += 1; v[i].first -= 2*r+2; ans += max(v[i].first, 0); r += 2; } } cout << n-ans << '\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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; vector<pair<int, int>> v; int l = 0; for (int i = 0; i < n; i++) { if (s[i] == '0') l++; else { v.push_back({l, 0}); l = 0; } } v.push_back({l, 0}); if (v.size() == 1) { cout << 0 << '\n'; continue; } v[0].first *= 2; v[0].second = 1; v.back().first *= 2; v.back().second = 1; sort(v.begin(), v.end(), [](pair<int, int>a, pair<int, int> b) { if (a.first != b.first) return a.first > b.first; return a.second > b.second; }); int r = 0, ans = 0; for (int i = 0; i < v.size(); i++) { if (v[i].second == 1) { ans += max(0, v[i].first/2-r); r++; } else if (v[i].first > 2*r) { ans += 1; v[i].first -= 2*r+2; ans += max(v[i].first, 0); r += 2; } } cout << n-ans << '\n'; } } |