#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int m;
cin >> m;
while (m--)
{
int n;
cin >> n;
string str;
cin >> str;
vector<pair<int, int>> data; //size, degree
vector<pair<float, int>> dieOuts; //die out, data index
bool firstOne = false;
int count = 0;
for (auto it : str)
{
if (it == '0')
{
count++;
}
else
{
if (count > 0)
{
if (!firstOne)
{
data.push_back({ count, 1 });
dieOuts.push_back({ (float)count, data.size() - 1 });
}
else
{
data.push_back({ count, 2 });
dieOuts.push_back({ (float)count / 2, data.size() - 1 });
}
count = 0;
}
firstOne = true;
}
}
if (!firstOne)
{
cout << "0\n";
continue;
}
if (count > 0)
{
data.push_back({ count, 1 });
dieOuts.push_back({ (float)count, data.size() - 1 });
}
sort(dieOuts.begin(), dieOuts.end());
int healthyTotal = 0;
int timePassed = 0;
for (int i = dieOuts.size() - 1; i >= 0; i--)
{
pair<int, int> current = data[dieOuts[i].second];
if (current.second == 1)
{
n -= max(current.first - timePassed, 0);
timePassed++;
}
else
{
if (current.first - timePassed * 2 - 1 == 0)
{
n--;
}
n -= max(current.first - timePassed * 2 - 1, 0);
timePassed += 2;
}
}
cout << n << '\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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int m; cin >> m; while (m--) { int n; cin >> n; string str; cin >> str; vector<pair<int, int>> data; //size, degree vector<pair<float, int>> dieOuts; //die out, data index bool firstOne = false; int count = 0; for (auto it : str) { if (it == '0') { count++; } else { if (count > 0) { if (!firstOne) { data.push_back({ count, 1 }); dieOuts.push_back({ (float)count, data.size() - 1 }); } else { data.push_back({ count, 2 }); dieOuts.push_back({ (float)count / 2, data.size() - 1 }); } count = 0; } firstOne = true; } } if (!firstOne) { cout << "0\n"; continue; } if (count > 0) { data.push_back({ count, 1 }); dieOuts.push_back({ (float)count, data.size() - 1 }); } sort(dieOuts.begin(), dieOuts.end()); int healthyTotal = 0; int timePassed = 0; for (int i = dieOuts.size() - 1; i >= 0; i--) { pair<int, int> current = data[dieOuts[i].second]; if (current.second == 1) { n -= max(current.first - timePassed, 0); timePassed++; } else { if (current.first - timePassed * 2 - 1 == 0) { n--; } n -= max(current.first - timePassed * 2 - 1, 0); timePassed += 2; } } cout << n << '\n'; } } |
English