#include <algorithm> #include <stdio.h> #include <vector> struct Section { int size; bool isCombo; bool operator<(const Section &s) const { return value() < s.value(); } private: int value() const { if (isCombo) return size; else return size * 2; } }; int solve(int n, const char *data) { std::vector<Section> sections; int size{0}, wirus{0}; bool isCombo{false}; for (int i = 0; i < n; ++i) { if (data[i] == '0') { size++; } else { if (size > 0) { sections.push_back({size, isCombo}); } size = 0; isCombo = true; wirus++; } } if (size > 0) { sections.push_back({size, false}); } std::sort(sections.rbegin(), sections.rend()); int time{0}; for (const auto §ion : sections) { if (section.isCombo) { if (section.size == time * 2 + 1) { wirus += section.size - 1; time++; } else { wirus += std::max(0, section.size - std::max(0, section.size - 2 * time - 1)); time += 2; } } else { wirus += std::max(0, section.size - std::max(0, section.size - time)); time++; } } return wirus; } int main() { int t, n; scanf("%d\n", &t); char data[100001]; for (int i = 1; i <= t; ++i) { scanf("%d\n", &n); scanf("%s\n", data); printf("%d\n", solve(n, data)); } 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 87 88 89 90 91 92 | #include <algorithm> #include <stdio.h> #include <vector> struct Section { int size; bool isCombo; bool operator<(const Section &s) const { return value() < s.value(); } private: int value() const { if (isCombo) return size; else return size * 2; } }; int solve(int n, const char *data) { std::vector<Section> sections; int size{0}, wirus{0}; bool isCombo{false}; for (int i = 0; i < n; ++i) { if (data[i] == '0') { size++; } else { if (size > 0) { sections.push_back({size, isCombo}); } size = 0; isCombo = true; wirus++; } } if (size > 0) { sections.push_back({size, false}); } std::sort(sections.rbegin(), sections.rend()); int time{0}; for (const auto §ion : sections) { if (section.isCombo) { if (section.size == time * 2 + 1) { wirus += section.size - 1; time++; } else { wirus += std::max(0, section.size - std::max(0, section.size - 2 * time - 1)); time += 2; } } else { wirus += std::max(0, section.size - std::max(0, section.size - time)); time++; } } return wirus; } int main() { int t, n; scanf("%d\n", &t); char data[100001]; for (int i = 1; i <= t; ++i) { scanf("%d\n", &n); scanf("%s\n", data); printf("%d\n", solve(n, data)); } return 0; } |