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
#include <iostream>
#include <algorithm>
using namespace std;

int tests, n;
int periods[100007];
 
int main()
{
  ios_base::sync_with_stdio(0);

  cin >> tests;

  for (int t=0; t<tests; t++) {
    cin >> n;
    int start = 0, sick = 0, current = 0, per_num = 0;
    char c;

    for (int i=0; i<n; i++) {
      cin >> c;
      if (c == '1') {
        sick++;
        if (current > 0) { // some period just finished
          if (sick == 1) { // this is the start, not a proper period
            start = current;
          }
          else {
            periods[per_num] = current;
            per_num++;
          }
          current = 0;
        }
      }
      else { // c == '0'
        current++;
      }
    }
    int end = current;

    if (sick == 0)
      cout << 0 << '\n'; // nothing to do
    else {
      int day = 0;
      sort(periods, periods + per_num);
      for (int i=0; i<per_num; i++) {
        if (periods[i] >= 2 * day + 3) {
          sick += 2 * day + 1;
          day += 2;
        }
        else if ((periods[i] >= 2 * day + 1) && (max(start, end) <= day )) {
          sick += periods[i] - 1;
          day++;
        }
        else
          sick += periods[i];
      }
      if (start > day) {
        sick += day;
        day++;
      }
      else
        sick += start;
      if (end > day) {
        sick += day;
        day++;
      }
      else
        sick += end;
      cout << sick << '\n';
    }
  }
  return 0;
}