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

priority_queue<int> zJedym;
priority_queue<int> zDwoma;
//reduces complexity from NlogN to N
vector<int> zJedymVect;
vector<int> zDwomaVect;
int offsetZJedym = 0, offsetZDwoma = 0;

int tick(int n)
{
    offsetZJedym = 0;
    offsetZDwoma = 0;
    int uratowane = 0;
    while(true)
    {
        int i = zJedym.empty() ? -1 : zJedym.top() - offsetZJedym;
        int j = zDwoma.empty() ? -1 : zDwoma.top() - offsetZDwoma;
        if(i <= 0 && j <= 0) return n - uratowane;
        if(i >= j)
        {
            uratowane += i;
            zJedym.pop();
        }
        else
        {
            uratowane++;
            zJedym.push(zDwoma.top() - offsetZDwoma - 1);
            zDwoma.pop();
        }
        offsetZJedym++;
        offsetZDwoma += 2;
    }
    return n - uratowane;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t; cin>>t;
    while(t--)
    {
        int n; cin>>n;
        string s; cin>>s;
        int wrog = 0;
        int currLen = 0;
        for(int i = 0; i < n; i++)
        {
            if(s[i] == '0')
            {
                currLen++;
            }
            else
            {
                if(currLen > 0)
                {
                    if(wrog == 1) zDwomaVect.push_back(currLen);
                    else zJedymVect.push_back(currLen);
                }
                wrog = 1;
                currLen = 0;
            }
        }
        if(currLen == n)
        {
            cout<<0<<'\n';
            continue;
        }
        else if(currLen > 0)
        {
            zJedymVect.push_back(currLen);
        }
        zJedym = priority_queue<int>(zJedymVect.begin(), zJedymVect.end());
        zDwoma = priority_queue<int>(zDwomaVect.begin(), zDwomaVect.end());
        cout<<tick(n)<<'\n';
        zJedymVect = vector<int>();
        zDwomaVect = vector<int>();
    }
    return 0;
}