#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while(t--)
{
vector <pair <int, int>> a;
int n;
string s;
cin >> n >> s;
s += '1';
int pop = 0;
for(int i = 0; i <= n; ++i)
{
if(s[i-1] == '0' && s[i] == '1')
{
if(pop != 0 && i != n) a.push_back({i-pop, 1});
else a.push_back({2*(i-pop), 0});
}
if(s[i-1] == '1' && s[i] == '0') pop = i;
}
sort(a.begin(), a.end(), greater <pair <int, int>>());
//for(int i = 0; i < a.size(); ++i) cout << a[i].first << " " << a[i].second << "\n";
int czas = 0, wyn = n;
for(int i = 0; i < a.size(); ++i)
{
if(a[i].second == 1)
{
if(a[i].first - czas*2 == 1)
{
wyn -= 1;
czas += 1;
}
else if(a[i].first-1 - czas*2 > 0)
{
wyn -= a[i].first-1 - czas*2;
czas += 2;
}
}
else
{
if(a[i].first/2 - czas > 0)
{
wyn -= a[i].first/2 - czas;
czas += 1;
}
}
}
cout << wyn << "\n";
}
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 | #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--) { vector <pair <int, int>> a; int n; string s; cin >> n >> s; s += '1'; int pop = 0; for(int i = 0; i <= n; ++i) { if(s[i-1] == '0' && s[i] == '1') { if(pop != 0 && i != n) a.push_back({i-pop, 1}); else a.push_back({2*(i-pop), 0}); } if(s[i-1] == '1' && s[i] == '0') pop = i; } sort(a.begin(), a.end(), greater <pair <int, int>>()); //for(int i = 0; i < a.size(); ++i) cout << a[i].first << " " << a[i].second << "\n"; int czas = 0, wyn = n; for(int i = 0; i < a.size(); ++i) { if(a[i].second == 1) { if(a[i].first - czas*2 == 1) { wyn -= 1; czas += 1; } else if(a[i].first-1 - czas*2 > 0) { wyn -= a[i].first-1 - czas*2; czas += 2; } } else { if(a[i].first/2 - czas > 0) { wyn -= a[i].first/2 - czas; czas += 1; } } } cout << wyn << "\n"; } return 0; } |
English