#include <iostream> #include <vector> #include <algorithm> using namespace std; struct interv{ int length; bool special; }; int t, n; char c; vector<interv> intervals; bool compare(interv a, interv b) { if(a.special == b.special) { return a.length > b.length; } else if(!a.special && b.special) { return a.length > b.length*2; } else { // if(a.special && !b.special) return a.length*2 > b.length; } } int main() { cin >> t; while(t --> 0) { vector<interv>().swap(intervals); cin >> n; int length = 0; for(int i=0; i<n; i++) { cin >> c; if(c == '0') length++; else { if(length != 0) { intervals.push_back({length, length == i}); length = 0; } } } if(length > 0) intervals.push_back({length,true}); sort(intervals.begin(), intervals.end(), compare); int days_spent = 0; int survived = 0; for(int i=0; i<intervals.size(); i++) { if(intervals[i].special) { if(days_spent >= intervals[i].length) break; survived += intervals[i].length-days_spent; days_spent++; } else { length = intervals[i].length-days_spent*2; if(length <= 0) break; if(length <= 2) { survived++; days_spent++; } else { survived += length-1; days_spent += 2; } } } cout << n-survived << endl; } }
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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; struct interv{ int length; bool special; }; int t, n; char c; vector<interv> intervals; bool compare(interv a, interv b) { if(a.special == b.special) { return a.length > b.length; } else if(!a.special && b.special) { return a.length > b.length*2; } else { // if(a.special && !b.special) return a.length*2 > b.length; } } int main() { cin >> t; while(t --> 0) { vector<interv>().swap(intervals); cin >> n; int length = 0; for(int i=0; i<n; i++) { cin >> c; if(c == '0') length++; else { if(length != 0) { intervals.push_back({length, length == i}); length = 0; } } } if(length > 0) intervals.push_back({length,true}); sort(intervals.begin(), intervals.end(), compare); int days_spent = 0; int survived = 0; for(int i=0; i<intervals.size(); i++) { if(intervals[i].special) { if(days_spent >= intervals[i].length) break; survived += intervals[i].length-days_spent; days_spent++; } else { length = intervals[i].length-days_spent*2; if(length <= 0) break; if(length <= 2) { survived++; days_spent++; } else { survived += length-1; days_spent += 2; } } } cout << n-survived << endl; } } |