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
#include <iostream>
#include <string>
#include <queue>
using namespace std;

struct segment {
    int deadline;
    int initial_size;
    char sides;

    segment(int sz, char sides) {
        this->sides = sides;
        this->initial_size = sz;
        this->deadline = sz / sides;
    }

    bool operator < (const struct segment& rhs) const {
        return this->deadline < rhs.deadline || (this->deadline == rhs.deadline && this->sides < rhs.sides) || (this->deadline == rhs.deadline && this->sides == rhs.sides && this->initial_size < rhs.initial_size);
    }
};

int main() {
    ios::sync_with_stdio(false); cin.tie();
    int t; cin >> t; while(t--) {
        priority_queue<segment> q;
        int n; string s; cin >> n >> s;
        bool first = true;
        int count = 0;
        for (char c : s) {
            if (c == '0') count++;
            else {
                if (count) {
                    char sides = first ? 1 : 2;
                    q.push({ count, sides });
                    count = 0;
                }
                first = false;
            }
        }

        if (count) q.push({ count, 1 });

        int days = 0;
        int saved = 0;
        while (!q.empty()) {
            segment cur = q.top(); q.pop();
            int current_size = cur.initial_size - cur.sides * days;
            //cerr << "Day " << days << ": Processing " << (int)cur.sides << "-sided segment with initial size "
                //<< cur.initial_size << " (now size " << current_size << ", deadline " << cur.deadline << ")\n";
            if (current_size <= 0) continue;

            days++;
            if (cur.sides > 1 && current_size > 1) {
                saved++;
                current_size--;
                q.push({ current_size + days - 1, 1 });
            } else {
                saved += current_size;
            }
        }

        cout << n - saved << '\n';
    }
}