#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int z; cin >> z; while (z--) { int n; cin >> n; string S; cin >> S; vector<pair<int, bool>> V; char prev = 0; for (auto& s : S) { if (s == '0') { if (s == prev) V.back().first++; else V.push_back({ 1, false }); } prev = s; } if (S.front() == '0') V.front() = { V.front().first * 2, true }; if (S.back() == '0') V.back() = { V.back().first * 2, true }; if (V.size() == 1 && S.front() == '0' && S.back() == '0') V.front().first /= 2; sort(V.rbegin(), V.rend()); int res = 0, day = 0; for (auto [v, b] : V) { v -= 2 * day; if (b) v /= 2; if (v <= 0) continue; if (b || v == 1) res += v, day++; else if (v == 2) res += 1, day++; else res += v - 1, day += 2; } cout << n - res << '\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 | #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int z; cin >> z; while (z--) { int n; cin >> n; string S; cin >> S; vector<pair<int, bool>> V; char prev = 0; for (auto& s : S) { if (s == '0') { if (s == prev) V.back().first++; else V.push_back({ 1, false }); } prev = s; } if (S.front() == '0') V.front() = { V.front().first * 2, true }; if (S.back() == '0') V.back() = { V.back().first * 2, true }; if (V.size() == 1 && S.front() == '0' && S.back() == '0') V.front().first /= 2; sort(V.rbegin(), V.rend()); int res = 0, day = 0; for (auto [v, b] : V) { v -= 2 * day; if (b) v /= 2; if (v <= 0) continue; if (b || v == 1) res += v, day++; else if (v == 2) res += 1, day++; else res += v - 1, day += 2; } cout << n - res << '\n'; } } |