#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; struct Interval { long long opened, length; Interval(long long opened, long long length) { this->opened = opened; this->length = length; } }; struct ord { inline bool operator() (const Interval& in1, const Interval& in2) { return (2 - in2.opened) * in2.length < (2 - in1.opened) * in1.length; } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); long long t; cin >> t; for (; t > 0; t--) { long long n, range = 0, left = 1; string str; cin >> n >> str; str.append("#"); vector<Interval> v; for (int i = 0; i <= n; i++) { if (str[i] == '0') { range += 1; } else { if (range > 0) { if (left || str[i] == '#') { Interval in(0, range); v.push_back(in); } else { Interval in(1, range); v.push_back(in); } } range = 0; left = 0; } } long long acc = 0, steps = 0; sort(v.begin(), v.end(), ord()); for (int i = 0; i < v.size(); i++) { if (v[i].opened == 0) { if (v[i].length - steps > 0) { acc += v[i].length - steps; } steps += 1; } else { if (v[i].length - 2 * steps > 0) { long long add = v[i].length - 2 * steps - 1; if (add < 1) { add = 1; } acc += add; } steps += 2; } } long long res = n - acc; cout << res << 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 | #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; struct Interval { long long opened, length; Interval(long long opened, long long length) { this->opened = opened; this->length = length; } }; struct ord { inline bool operator() (const Interval& in1, const Interval& in2) { return (2 - in2.opened) * in2.length < (2 - in1.opened) * in1.length; } }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); long long t; cin >> t; for (; t > 0; t--) { long long n, range = 0, left = 1; string str; cin >> n >> str; str.append("#"); vector<Interval> v; for (int i = 0; i <= n; i++) { if (str[i] == '0') { range += 1; } else { if (range > 0) { if (left || str[i] == '#') { Interval in(0, range); v.push_back(in); } else { Interval in(1, range); v.push_back(in); } } range = 0; left = 0; } } long long acc = 0, steps = 0; sort(v.begin(), v.end(), ord()); for (int i = 0; i < v.size(); i++) { if (v[i].opened == 0) { if (v[i].length - steps > 0) { acc += v[i].length - steps; } steps += 1; } else { if (v[i].length - 2 * steps > 0) { long long add = v[i].length - 2 * steps - 1; if (add < 1) { add = 1; } acc += add; } steps += 2; } } long long res = n - acc; cout << res << endl; } return 0; } |