-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1430d.cpp
More file actions
78 lines (75 loc) · 1.74 KB
/
Copy path1430d.cpp
File metadata and controls
78 lines (75 loc) · 1.74 KB
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
/**
* author: vishnus
* created: 2022-08-22
**/
#include <bits/stdc++.h>
using namespace std;
// Idea: if the prefix that is to be removed has more than 1 element, just remove one element from there
// and let the prefix remove itself. Otherwise, we want to manually remove the most indices that are a
// part of future prefix, since those elements will be removed anyways. Use a set to do that and remove
// from the closest future prefix.
int main() {
#ifdef ONLINE_JUDGE
ios::sync_with_stdio(false);
cin.tie(0);
#endif
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
deque<int> a(n);
for (int i = 0; i < n; i++) {
char c;
cin >> c;
a[i] = (c == '1');
}
deque<pair<int, int>> comp;
int cur_c = a[0];
int cnt = 1;
for (int i = 1; i < n; i++) {
if (a[i] == cur_c) {
cnt++;
} else {
comp.push_back({cur_c, cnt});
cur_c = a[i];
cnt = 1;
}
}
comp.push_back({cur_c, cnt});
set<int> mult;
for (int i = 0; i < (int) comp.size(); i++) {
if (comp[i].second > 1) {
mult.insert(i);
}
}
int ans = 0;
int decr = 0;
while (!comp.empty()) {
if ((int) comp.size() == 1 && comp[0].second == 1) {
ans++;
break;
}
if (comp[0].second != 1) {
ans++;
comp.pop_front();
mult.erase(decr);
decr++;
} else {
ans++;
if (!mult.empty()) {
int idx = (*mult.begin()) - decr;
comp[idx].second--;
if (comp[idx].second == 1) {
mult.erase(mult.begin());
}
} else {
comp.pop_back();
}
comp.pop_front();
decr++;
}
}
cout << ans << '\n';
}
}