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
#include <bits/stdc++.h>
using namespace std;
bool tab[100009];
int main()
{ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int q;
    cin>>q;
for(int I=1;I<=q;I++)
{
    int n;
    string A;
    cin>>n>>A;
    int wynik=0;
    for(int i=1;i<=n;i++)
    {
        tab[i]=A[i-1]-48;
        if(tab[i]==1){wynik++;}
    }
    if(wynik==0||wynik==n){cout<<wynik<<endl;continue;}
    set<pair<int,int>>S1,S2;
    int gh=0;
    for(int i=1;i<=n;i++)
    {
        if(tab[i]==1){gh=i;break;}
    }
    if(gh!=1)
    {
       S1.insert({gh-1,0});
    }
    int wielkosc=0;
    int h=0;
    for(int i=gh;i<=n;i++)
    {
        if(tab[i]==1)
        {
            if(wielkosc!=0)
            {
                h++;
                S2.insert({wielkosc,h});
                wielkosc=0;
            }
        }
        else
        {
            wielkosc++;
        }
    }
    if(wielkosc!=0)
    {
        h++;
        S1.insert({wielkosc,h});
    }
    for(int i=0;true;i++)
    {
        while(S1.size()>0&&S1.begin()->first<=i)
        {
            S1.erase(*S1.begin());
        }
        while(S2.size()>0&&S2.begin()->first<=2*i)
        {
            S2.erase(*S2.begin());
        }
        while(S2.size()>0&&S2.begin()->first==2*i+1)
        {
            S2.erase(*S2.begin());
            h++;
            S1.insert({i+1,h});
        }
        if(S1.size()>0&&S2.size()>0)
        {
            int u1=S1.rbegin()->first-i;
            int u2=S2.rbegin()->first-(2*i);
            if(2*u1>u2)
            {
                S1.erase(*S1.rbegin());
            }
            else
            {
                u2+=i;
                S2.erase(*S2.rbegin());
                h++;
                S1.insert({u2,h});
            }
        }
        else if(S2.size()>0)
        {
            int u=S2.rbegin()->first;
            u-=2*i;
            u+=i;
            S2.erase(*S2.rbegin());
            h++;
            S1.insert({u,h});
        }
        else if(S1.size()>0)
        {
            S1.erase(*S1.rbegin());
        }
        if(S1.size()==0&&S2.size()==0){break;}
        wynik+=S1.size()+(2*S2.size());
    }
    cout<<wynik<<endl;
}
    return 0;
}
/**
1
8
00110100

1
8
10001000
**/