#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
priority_queue<pair<ll, bool>> Q; //rozmiar pola i rodzaj 1 lub 2
void task(ll n, string s) {
ll p = 0;
ll ans = 1;
while (s[p] == '0' && p < n) p++;
if (p > 0) Q.push({ 2*p, 0 });
if (p == n) {
cout << 0;
return;
}
ll r = 0;
for (ll i = p + 1; i < n; i++) {
if (s[i] == '1') {
ans++;
if (r > 0) Q.push({ r, 1 });
r = 0;
}
else r++;
}
if (r > 0) Q.push({ 2*r, 0 });
ll k = 0;
while (!Q.empty()) {
pair<ll, bool>v = Q.top();
Q.pop();
if (v.second == 0) {
ans += min(v.first/2, k);
}
else {
ll akt = 0;
if (k <= (v.first + 1) / 2) {
akt += 2 * k;
if (v.first % 2 == 1 && akt > 0)
akt--;
ans += akt;
v.first -= (akt + 1);
v.first *= 2;
v.second = 0;
if(v.first > 0)
Q.push(v);
}
else ans += v.first;
}
k++;
}
cout << ans << "\n";
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll t, n;
string s;
cin >> t;
for (ll i = 0; i < t; i++) {
cin >> n >> s;
task(n, s);
}
}
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 | #include <iostream> #include <queue> #include <algorithm> using namespace std; typedef long long ll; priority_queue<pair<ll, bool>> Q; //rozmiar pola i rodzaj 1 lub 2 void task(ll n, string s) { ll p = 0; ll ans = 1; while (s[p] == '0' && p < n) p++; if (p > 0) Q.push({ 2*p, 0 }); if (p == n) { cout << 0; return; } ll r = 0; for (ll i = p + 1; i < n; i++) { if (s[i] == '1') { ans++; if (r > 0) Q.push({ r, 1 }); r = 0; } else r++; } if (r > 0) Q.push({ 2*r, 0 }); ll k = 0; while (!Q.empty()) { pair<ll, bool>v = Q.top(); Q.pop(); if (v.second == 0) { ans += min(v.first/2, k); } else { ll akt = 0; if (k <= (v.first + 1) / 2) { akt += 2 * k; if (v.first % 2 == 1 && akt > 0) akt--; ans += akt; v.first -= (akt + 1); v.first *= 2; v.second = 0; if(v.first > 0) Q.push(v); } else ans += v.first; } k++; } cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll t, n; string s; cin >> t; for (ll i = 0; i < t; i++) { cin >> n >> s; task(n, s); } } |
English