#include <iostream> #include <vector> #include <algorithm> using namespace std; #define FOR(name, start, upper) for(int name = start; name < upper; ++name) string tab; vector <pair<int,int>> lenghts; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--) { tab.clear(); lenghts.clear(); int n = 0, sum = 0; tab.resize(n); cin >> n; FOR(i, 0, n) { cin >> tab[i]; if(tab[i] == '1') sum++; } int p = 0; FOR(i, 1, n) { if(tab[i] == '1' && tab[i-1] == '0') { pair<int,int> a; a.first = i-p; a.second = p; lenghts.push_back(a); } if(tab[i] == '0' && tab[i-1] == '1') { p = i; } } if(tab[n-1] == '0') { lenghts.push_back({n-p, p}); } sort(lenghts.begin(), lenghts.end(), greater<pair<int,int>>()); int i = 0; FOR(k, 0, lenghts.size()) { int x = lenghts[k].first; if(lenghts[k].second == 0 || lenghts[k].second+x == n) { if(i >= x) { sum += x; } else { sum += i; } } else if(2*i >= x) { sum += x; } else { if(x-2*i > 1) sum += (2*i+1); if(x > 2) i++; } i++; } cout << sum << "\n"; } }
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 <vector> #include <algorithm> using namespace std; #define FOR(name, start, upper) for(int name = start; name < upper; ++name) string tab; vector <pair<int,int>> lenghts; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--) { tab.clear(); lenghts.clear(); int n = 0, sum = 0; tab.resize(n); cin >> n; FOR(i, 0, n) { cin >> tab[i]; if(tab[i] == '1') sum++; } int p = 0; FOR(i, 1, n) { if(tab[i] == '1' && tab[i-1] == '0') { pair<int,int> a; a.first = i-p; a.second = p; lenghts.push_back(a); } if(tab[i] == '0' && tab[i-1] == '1') { p = i; } } if(tab[n-1] == '0') { lenghts.push_back({n-p, p}); } sort(lenghts.begin(), lenghts.end(), greater<pair<int,int>>()); int i = 0; FOR(k, 0, lenghts.size()) { int x = lenghts[k].first; if(lenghts[k].second == 0 || lenghts[k].second+x == n) { if(i >= x) { sum += x; } else { sum += i; } } else if(2*i >= x) { sum += x; } else { if(x-2*i > 1) sum += (2*i+1); if(x > 2) i++; } i++; } cout << sum << "\n"; } } |