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 <bits/stdc++.h>
#define PB push_back
#define ALL(c) (c).begin(), (c).end()
#define SIZE(x) (int)(x).size()
using namespace std;
typedef vector<int> VI;

const int N = 1e5 + 10;

int n;
char s[N+1];

struct Bag {
  priority_queue<int, VI, greater<>> q;
  int day = 0, sum = 0;

  void add(int x) {
    q.push(x);
    sum += x;
    fix();
  }
  void kill() {
    ++day;
    fix();
  }
  void fix() {
    while (!q.empty() && q.top() <= SIZE(q) - 1 + day) {
      sum -= q.top();
      q.pop();
    }
  }
  int res() {
    int n = SIZE(q);
    return sum - n*(n-1)/2 - n*day;
  }
};

int main() {
  int t; scanf("%d", &t);
  while (t--) {
    scanf("%d%s", &n, s);
    VI one, two;
    for (int i = 0; i < n; ++i) if (s[i] == '0') {
      int l = 1;
      while (i + l < n && s[i + l] == '0') ++l;
      (l == 1 || i == 0 || i + l == n ? one : two).PB(l);
      i += l;
    }

    Bag bag;
    for (int x: one) bag.add(x);
    int r = bag.res();

    sort(ALL(two), greater<>());
    for (int x: two) {
      bag.kill();
      bag.add(x);
      r = max(r, bag.res());
    }

    printf("%d\n", n - r);
  }
  return 0;
}