#include <iostream> #include <vector> #include <string> using namespace std; struct Block { int len, dec; }; void vector_pop(vector<Block>&V, int i) { swap(V[i], V.back()); V.pop_back(); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n; string str; cin >> n >> str; //build blocks vector<Block>B; int acc = 0; for (int i = 0; i < n; i++) if (str[i]=='0') acc++; else if(acc) { B.push_back(Block{.len=acc, .dec=2}); acc = 0; } if (acc) B.push_back(Block{.len=acc, .dec=2}); if (str.front()=='0') B.front().dec--; if (str.back()=='0') B.back().dec--; if (B.size()==1 && B[0].dec == 0) { cout << "0\n"; continue; } int vac = 0; while (!B.empty()) { //find biggest int biggest_in_danger_i, biggest_in_danger_points = -1000; for (int i = 0; i < (int)B.size(); i++) { int points = B[i].len - 2*B[i].dec; if (points > biggest_in_danger_points) { biggest_in_danger_i = i; biggest_in_danger_points = points; } } //do it vac++; B[biggest_in_danger_i].dec--; B[biggest_in_danger_i].len--; if (B[biggest_in_danger_i].dec == 0 || B[biggest_in_danger_i].len == 0) { vac += B[biggest_in_danger_i].len; vector_pop(B, biggest_in_danger_i); } //virus propagate for (int i = 0; i < (int)B.size();) { B[i].len -= B[i].dec; if (B[i].len <= 0) vector_pop(B, i); else i++; } } cout << n - vac << 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 | #include <iostream> #include <vector> #include <string> using namespace std; struct Block { int len, dec; }; void vector_pop(vector<Block>&V, int i) { swap(V[i], V.back()); V.pop_back(); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n; string str; cin >> n >> str; //build blocks vector<Block>B; int acc = 0; for (int i = 0; i < n; i++) if (str[i]=='0') acc++; else if(acc) { B.push_back(Block{.len=acc, .dec=2}); acc = 0; } if (acc) B.push_back(Block{.len=acc, .dec=2}); if (str.front()=='0') B.front().dec--; if (str.back()=='0') B.back().dec--; if (B.size()==1 && B[0].dec == 0) { cout << "0\n"; continue; } int vac = 0; while (!B.empty()) { //find biggest int biggest_in_danger_i, biggest_in_danger_points = -1000; for (int i = 0; i < (int)B.size(); i++) { int points = B[i].len - 2*B[i].dec; if (points > biggest_in_danger_points) { biggest_in_danger_i = i; biggest_in_danger_points = points; } } //do it vac++; B[biggest_in_danger_i].dec--; B[biggest_in_danger_i].len--; if (B[biggest_in_danger_i].dec == 0 || B[biggest_in_danger_i].len == 0) { vac += B[biggest_in_danger_i].len; vector_pop(B, biggest_in_danger_i); } //virus propagate for (int i = 0; i < (int)B.size();) { B[i].len -= B[i].dec; if (B[i].len <= 0) vector_pop(B, i); else i++; } } cout << n - vac << endl; } return 0; } |