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
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

void solve() {
  int n; scanf("%d", &n);

  priority_queue<int> singles, doubles;

  int len = 0;
  bool first = true;
  for (int i=0; i<n; ++i) {
    char c; scanf(" %c", &c);
    if (c == '1') {
      if (len > 0) {
        if (first) {
          singles.push(len);
        } else {
          doubles.push(len);
        }
      }
      len = 0;
      first = false;
    } else {
      ++len;
    }
  }
  if (len > 0) {
    singles.push(len);
  }

  int res = 0;
  int steps = 0;
  while (true) {
//    printf("Step: %d\n", steps);
    if (!singles.empty() &&
          singles.top() > steps &&
          (doubles.empty() ||
            singles.top() * 2 >= doubles.top() - 1)) {
//      printf("Clearing single: %d -> %d\n", singles.top(), singles.top() - steps);
      res += singles.top() - steps;
      singles.pop();
    } else if (!doubles.empty() && doubles.top() > steps * 2) {
//      printf("Clearing double: %d -> 1 (side effect: %d)\n", doubles.top(), doubles.top() - steps - 1);
      res += 1;
      singles.push(doubles.top() - steps - 1);
      doubles.pop();
    } else {
      break;
    }
    ++steps;
  }

  printf("%d\n", n - res);
}

int main() {
  int t; scanf("%d", &t);
  for (int tt=0; tt<t; ++tt) solve();
}