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
#include<bits/stdc++.h>
using namespace std;

struct TownGroup{
    int numberOfTowns;
    int infectedNeighbours;
    double proportion;
    TownGroup(int numberOfTowns, int infectedNeighbours){
        this->numberOfTowns = numberOfTowns;
        if(infectedNeighbours == 0){
            proportion = numberOfTowns;
            this->infectedNeighbours = 1;
        }
        else{
            this->infectedNeighbours = infectedNeighbours;
            proportion = 1.0*numberOfTowns/infectedNeighbours;
        }
    }

    int calcValue(int time){
        int calc = numberOfTowns-infectedNeighbours*time;
        if(calc > 1) calc -= (infectedNeighbours-1);
        return calc;
    }
};

bool townGroupPriority(TownGroup * fst, TownGroup * snd){
    return fst->proportion > snd->proportion;
}

int main(){
    ios_base::sync_with_stdio(0);
    int t;
    cin >> t;

    while(t--){
        int n;
        cin >> n;

        string s;
        cin >> s;

        int current_healthy_town_counter = 0;
        int infected_neighbours = 0;
        if(s[0] == '1') infected_neighbours = 1;

        vector<TownGroup*> town_groups;
        for(int i=0; i<n; i++){
            if(s[i] == '0'){
                ++current_healthy_town_counter;
            } else if(s[i] == '1' && current_healthy_town_counter > 0){
                town_groups.push_back(new TownGroup(current_healthy_town_counter, infected_neighbours+1));
                current_healthy_town_counter = 0;
                infected_neighbours = 1;
            }
        }
        if(current_healthy_town_counter > 0){
            town_groups.push_back(new TownGroup(current_healthy_town_counter, infected_neighbours));
        }

        sort(town_groups.begin(), town_groups.end(), townGroupPriority);

        int time = 0, result = 0;
        for(int i=0; i<town_groups.size(); i++){
            TownGroup * current_town_group = town_groups[i];
            result += max(0, current_town_group->calcValue(time));
            time += current_town_group->infectedNeighbours;            
            delete current_town_group;
        }

        cout << n-result << "\n";
    }
}