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
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>

using namespace std;

void rozpatrz_przypadek(int n) {
  vector<int> k{};
  int temp = -1;
  int last_0 = -1;
  int input;
  char val;
  pair<int, int> krawedzie = make_pair(-1, -1);
  for (int i = 0; i < n; ++i) {
    cin >> val;
    input = int(val - '0');
    if (input == 0 && last_0 == -1) {
      last_0 = i;
    }
    if (input == 1 && last_0 != -1) {
      temp = (i - last_0);

      if (last_0 == 0) {
        get<0>(krawedzie) = temp;
      } else {
        k.push_back(temp);
      }
      last_0 = -1;
      temp = -1;
    }
  }
  if (last_0 != -1) {
    temp = n - last_0;
    get<1>(krawedzie) = temp;
  }

  if (krawedzie.first == krawedzie.second && krawedzie.first != -1) {
    k.push_back(krawedzie.first + krawedzie.second);
    krawedzie.first = -1;
    krawedzie.second = -1;
  }
  sort(k.begin(), k.end());

  int left_0 = 0;
  auto[a, d] = krawedzie;
  for (int i = 0;; i++) {
    int k1 = k.empty() ? -1 : k.back();
    if (k1 == -1 && a - i <= 0 && d - i <= 0) {
      break;
    }
    if (max(a, d) - i >= k1 - 2 * i - 1 && max(a, d) - i > 0) {
      if (a > d) {
        left_0 += a - i;
        a = -1;
      } else {
        left_0 += d - i;
        d = -1;
      }
    } else if (k1 - 2 * i - 1 > 0) {
      left_0 += k1 - 2 * i - 1;
      i++;
      k.pop_back();
    } else if (k1 - 2 * i - 1 == 0) {
      left_0 += 1;
      k.pop_back();
      break;
    } else {
      break;
    }
  }

  cout << n - left_0 << '\n';
}

int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);
  int t, n;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    cin >> n;
    rozpatrz_przypadek(n);
  }

  return 0;
}