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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
#include <iostream> // Kamil Zyczkowski
#include <string>
#include <queue>
using namespace std;

void solve()
{
    priority_queue<int> dwie, jedna;
    int n, ans = 0, day = 0, counter, lewa, prawa, x, y, z;
    string a;

    cin >> n >> a;

    lewa = prawa = 0;
    for(int i = 0; i < n; i++) {
        if(a[i] == '0')
            lewa++;
        else
            break;
    }
    if(lewa == n) {
        cout << 0;
        return;
    }
    for(int i = n - 1; i >= 0; i--) {
        if(a[i] == '0')
            prawa++;
        else
            break;
    }

    if(lewa != 0)
        jedna.push(lewa);
    if(prawa != 0)
        jedna.push(prawa);

    counter = 0;
    for(int i = lewa; i < n - prawa; i++) {
        if(a[i] == '0')
            counter++;
        else if(counter != 0) {
            dwie.push(counter);
            counter = 0;
        }
    }

    jedna.push(0); // zapobiegawcza na potem
    jedna.push(0);
    dwie.push(0);

    if(max(jedna.top(), dwie.top()) == 1) {
        cout << n - 1;
        return;
    }

    while (jedna.top() > day || dwie.top() > day * 2) {
        x = dwie.top();
        y = jedna.top(); jedna.pop();
        z = jedna.top(); jedna.push(y);

        if(y - day >= 2 && x - 2 * day <= 4) {
            jedna.pop();
            ans += (y - day);
        }
        else if(y + z >= x) {
            jedna.pop();
            ans += (y - day);
        }
        else if(y + 1 >= x - 1 && x - 2 * day >= 3) {
            jedna.pop();
            ans += (y - day);
        }
        else {
            dwie.pop();
            if(x - 2 * day <= 2)
                ans++;
            else {
                ans += (x - 2 * day - 1);
                day++;
            }
        }

        day++;
    }

    cout << n - ans; // ans - miasta ktore ocalaly
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int tc;
    cin >> tc;
    while(tc--) {
        solve();
        cout << '\n';
    }

    return 0;
}