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
#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;

#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()

template<typename _T> inline void _DBG(const char *s, _T x) { cerr << s << " = " << x << "\n"; }
template<typename _T, typename... args> void _DBG(const char *s, _T x, args... a) { while(*s != ',') cerr << *s++; cerr << " = " << x << ','; _DBG(s + 1, a...); }

#ifdef LOCAL
#define _upgrade ios_base::sync_with_stdio(0);
#define DBG(...) _DBG(#__VA_ARGS__, __VA_ARGS__)
#else
#define _upgrade ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define DBG(...) (__VA_ARGS__)
#define cerr if(0) cout
#endif

// ********************** CODE ********************** //

int f(const pair<int, int> &p)
{
    return 2 * ((3 - p.second) * p.first + (3 - p.second)) + (p.second - 1);
}

void solve_one_test_case()
{
    int n;
    cin >> n;

    string s;
    cin >> s;

    int ans = -1;

    vector<pair<int, int>> gaps;
    int last = -1;
    for (int i = 0; i <= n; i++)
    {
        if (i < n && s[i] == '0')
            continue;
        
        ans++;
        if (i > last + 1)
        {
            if (last == -1 || i == n)
                gaps.push_back({i - last - 1, 1});
            else
                gaps.push_back({i - last - 1, 2});
        }
        last = i;
    }

    while (gaps.size() > 0)
    {
        int min_id = 0;
        for (int i = 0; i < sz(gaps); i++)
        {
            if (f(gaps[i]) > f(gaps[min_id]))
                min_id = i;
        }

        swap(gaps[min_id], gaps.back());
        auto min_gap = gaps.back();
        gaps.pop_back();

        if (min_gap.second == 2)
            gaps.push_back({min_gap.first - 1, 1});
        
        for (int i = 0; i < sz(gaps); i++)
        {
            int k = min(gaps[i].first, gaps[i].second);
            ans += k;
            if (k < gaps[i].first)
            {
                gaps[i].first -= k;
            }
            else
            {
                swap(gaps[i], gaps.back());
                gaps.pop_back();
                i--;
            }
        }
    }

    cout << ans << "\n";
}

int main()
{
    _upgrade
    
    int t;
    cin >> t;

    while(t--)
        solve_one_test_case();   

    return 0;
}