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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <cstdio>
#include <cstdlib>

const int NN = 50500;

struct Dist {
  int size;
  int threat;
};

struct Map {
  Dist dists[NN];
  int length;
}theMap;

inline int _max(int a, int b) {
  if (a > b) {
    return a;
  } else {
    return b;
  }
}

Map *parse(char *str) {
  Map *r = &theMap;

  int count = 0;
  int threat = 0;
  int len = 0;
  for (; *str; ++str) {
    if (*str == '1') {
      if (len > 0) {
        r->dists[count++] = {.size = len, .threat = threat + 1};
        len = 0;
      }
      threat = 1;
    } else {
      ++len;
    }
  }
  if (len > 0) {
    r->dists[count++] = {.size = len, .threat = threat};
  }
  r->length = count;
  return r;
}

int dist_a_cmp(const void *a, const void *b) { return (*(const Dist **)b)->size - (*(const Dist **)a)->size; }

int pan(Map *map) {
  const int len = map->length;
  Dist *low[2];
  Dist *dists[NN];
  int lows = 0;
  int offset = 0;
  int postset = 0;
  int max = 0;
  int saved;
  int time;
  int place;

  
  for (int i = 0; i < len; ++i) {
    dists[i] = map->dists + i;
  }

  Dist *x;
  if (len > 0) {
    x = dists[0];
    if (x->threat == 1 && x->size > 1) {
      low[lows++] = x;
      ++offset;
    }
  }

  if (len - offset > 0) {
    x = dists[len - 1];
    if (x->threat == 1 && x->size > 1) {
      low[lows++] = x;
      ++postset;
    }
  }


  qsort(dists, len, sizeof(Dist *), dist_a_cmp);
  qsort(low, lows, sizeof(Dist *), dist_a_cmp);

  for (int cheat = 0; cheat < 3 && cheat <= lows; ++cheat) {
    saved = 0;
    time = 0;
    place = 0;
    for (int l = 0; l < lows; ++l) {
      low[l]->threat = 1;
    }
    for (; time < cheat; ++time) {
      saved += low[time]->size - time;
      low[time]->threat = -1;
    }
    for (; place < len; ++place) {
      Dist *curr = dists[place];
      if (curr->threat == 0) {
        saved = curr->size;
        break;
      }
      if (curr->threat == -1) {
        continue;
      }
      int left = curr->size - time * curr->threat - (curr->threat - 1);
      if (left == 0 && curr->threat == 2) {
        left = 1;
      }
      if (left <= 0) {
        break;
      } else {
        saved += left;
        time += curr->threat;
      }
    }
    max = _max(max, saved);
  }

  return max;
}

int main() {
  char str[100100];
  int t, n;
  scanf("%d", &t);
  while (t--) {
    scanf("%d%s", &n, str);
    Map *m = parse(str);
    int result = n - pan(m);
    printf("%d\n", result);
  }
  return 0;
}