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
#pragma GCC optimize ("Ofast")
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define FOR(i, a, b) for (auto i=(a); i<(b); i++)
#define FORD(i, a, b) for (int i=(a); i>(b); i--)
#define SZ(x) ((int)(x).size())
#define ALL(x) (x).begin(), (x).end()
#define PPC(x) __builtin_popcountll(x)
#define MSB(x) (63 - __builtin_clzll(x))
#define LSB(x) __builtin_ctz(x)
#define ARG(x, i) (get<i>(x))
#define ithBit(m, i) ((m) >> (i) & 1)
#define pb push_back
#define ft first
#define sd second
#define kw(a) ((a) * (a))
#ifdef DEBUG
#include "debug.h"
#else
#define dbg(...) 0
#endif
using namespace std; 

template <typename T1, typename T2> inline void remin(T1& a, T2 b) { a = min(a, (T1)b);	}
template <typename T1, typename T2> inline void remax(T1& a, T2 b) { a = max(a, (T1)b);	}
 
const int maxN = 1 << 17;

char T[maxN];

int pref(int n, bool rev = false)
{
	if (rev)	reverse(T, T+n);
	int ret = find(T, T+n, '1') - T;
	if (rev)	reverse(T, T+n);
	return ret;
}

vector <int> part(int n)
{
	int last = -1;
	vector <int> ret;
	FOR(i, 0, n) if (i+1 == n or T[i+1] != T[i])
	{
		if (T[i] == '0' and last != -1 and i != n-1)
			ret.pb(i - last);
		last = i;
	}
	return ret;
}

void solve()
{
	int n;
	scanf ("%d%s", &n, T);
	priority_queue <pair <int, int> > H;
	for (int x : {pref(n, false), pref(n, true)})
		if (x != 0 and x != n)
			H.push({x * 2, 1});
	for (int x : part(n))	
		H.push({x, 2});
		
	int res = count(T, T+n, '1');
		
	for (int t=0; !H.empty(); t++)
	{
		auto [x, tp] = H.top();
		H.pop();
		
		if (tp == 1)
		{
			res += min(t, x / 2);
			continue;
		}
		
		if (t * 2 >= x)
		{
			res += x;
			continue;
		}
		
		res += t;
		x -= t+1;
		H.push({x * 2, 1});
	}
	
	printf("%d\n", res);
}
 
int main()
{
	int t = 1;
	scanf ("%d", &t);
	FOR(tid, 1, t+1)
	{
		//printf("Case #%d: ", tid);
		solve();
	}
	return 0;
}