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
#include <cstdio>
#include <map>

int main ()
{
  int t;
  scanf ("%i", &t);
  while (t--)
  {
    std::map <int, int, std::greater <int>> A, B;
    int n, v = 0, u = 0, b = 0;
    scanf ("%i ", &n);
    for (int i=0; i<n; i++)
    {
      if (getchar () == '1')
      {
        if (u) (b? B: A) [u]++;
        v++;
        u = 0;
        b = 1;
      }
      else u++;
    }
    if (u && b) A [u]++;
    for (int d = 0; !A.empty () || !B.empty ();)
    {
      auto I = A.begin (), J = B.begin ();
      if (I==A.end () || (J!=B.end () && J->first > 2*I->first))
      {
        if (J->first-d>d+1) A [J->first-d]++; else v += d;
        if (!--J->second) B.erase (J);
      }
      else
      {
        if (!--I->second) A.erase (I);
      }
      v += d;
      if ((J = B.find (2*d+1)) != B.end ()) v += J->second*(2*d+1), B.erase (J);
      if ((J = B.find (2*++d)) != B.end ()) v += J->second*2*d,     B.erase (J);
      if ((I = A.find (d))     != A.end ()) v += I->second*d,       A.erase (I);
    }
    printf ("%i\n", v);
  }
  return 0;
}