#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
int T;
cin >> T;
for (int t = 0; t < T; t++) {
int N;
cin >> N;
string s;
cin >> s;
vector<int> v;
int edge1 = 0;
int edge2 = 0;
bool edge = true;
int cnt0 = 0;
for (auto c: s) {
if (c == '0') {
cnt0++;
} else {
if (cnt0 > 0) {
if (edge)
edge1 = cnt0;
else
v.push_back(cnt0);
cnt0 = 0;
}
edge = false;
}
}
if (cnt0 > 0) {
if (edge) {
cout << "0" << endl;
continue;
}
edge2 = cnt0;
}
sort(v.begin(), v.end());
int days = 0;
cnt0 = 0;
for (auto it = v.rbegin(); it != v.rend(); it++) {
int currentval = *it - 2*days;
auto getedge = [&] (int &edgeval) {
if ((edgeval - days >= currentval-1 && edgeval - days > 0) ||
(currentval == 5 && edgeval - days == 3)) {
cnt0 += edgeval - days;
days++;
edgeval = 0;
currentval -= 2;
}
};
getedge(edge2);
getedge(edge1);
if (currentval == 2 || currentval == 1) {
cnt0++;
days++;
} else if (currentval > 0) {
cnt0 += currentval-1;
days += 2;
}
}
if (edge1 - days > 0) {
cnt0 += edge1 - days;
days++;
}
if (edge2 - days > 0)
cnt0 += edge2 - days;
cout << N-cnt0 << endl;
}
return 0;
}
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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); int T; cin >> T; for (int t = 0; t < T; t++) { int N; cin >> N; string s; cin >> s; vector<int> v; int edge1 = 0; int edge2 = 0; bool edge = true; int cnt0 = 0; for (auto c: s) { if (c == '0') { cnt0++; } else { if (cnt0 > 0) { if (edge) edge1 = cnt0; else v.push_back(cnt0); cnt0 = 0; } edge = false; } } if (cnt0 > 0) { if (edge) { cout << "0" << endl; continue; } edge2 = cnt0; } sort(v.begin(), v.end()); int days = 0; cnt0 = 0; for (auto it = v.rbegin(); it != v.rend(); it++) { int currentval = *it - 2*days; auto getedge = [&] (int &edgeval) { if ((edgeval - days >= currentval-1 && edgeval - days > 0) || (currentval == 5 && edgeval - days == 3)) { cnt0 += edgeval - days; days++; edgeval = 0; currentval -= 2; } }; getedge(edge2); getedge(edge1); if (currentval == 2 || currentval == 1) { cnt0++; days++; } else if (currentval > 0) { cnt0 += currentval-1; days += 2; } } if (edge1 - days > 0) { cnt0 += edge1 - days; days++; } if (edge2 - days > 0) cnt0 += edge2 - days; cout << N-cnt0 << endl; } return 0; } |
English