#include<bits/stdc++.h> using namespace std; struct T { int len, cnt; }; bool operator< (const T& a, const T& b) { return a.len*b.cnt < b.len*a.cnt; } void query() { int n; string s; cin >> n >> s; if(s == string(n,'0')) { cout << "0\n"; return; } priority_queue<T> t; int len = 0, cnt = 1; for(char c : s) if(c == '0') len++; else { if(len > 0) t.push({len, cnt}); len = 0, cnt = 2; } if(len > 0) t.push({len,1}); int res = n; int tim = 0; while(!t.empty()) { auto x = t.top(); t.pop(); int left = x.len-tim*x.cnt; if(left > 0) { if(x.cnt == 1) res -= left; else { res--; x.cnt = 1; x.len -= tim+1; t.push(x); } tim++; } } cout << res << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int q; cin >> q; while(q--) query(); 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 | #include<bits/stdc++.h> using namespace std; struct T { int len, cnt; }; bool operator< (const T& a, const T& b) { return a.len*b.cnt < b.len*a.cnt; } void query() { int n; string s; cin >> n >> s; if(s == string(n,'0')) { cout << "0\n"; return; } priority_queue<T> t; int len = 0, cnt = 1; for(char c : s) if(c == '0') len++; else { if(len > 0) t.push({len, cnt}); len = 0, cnt = 2; } if(len > 0) t.push({len,1}); int res = n; int tim = 0; while(!t.empty()) { auto x = t.top(); t.pop(); int left = x.len-tim*x.cnt; if(left > 0) { if(x.cnt == 1) res -= left; else { res--; x.cnt = 1; x.len -= tim+1; t.push(x); } tim++; } } cout << res << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int q; cin >> q; while(q--) query(); return 0; } |