P11361 [NOIP2024] 编辑字符串 题解 | 趣味贪心
cancan123456 · · 个人记录
先说说考场思路(注意是错的)。
首先交换可以看作一段区间内重排,这样
考虑贪心,维护能交换到
从头到尾扫一遍序列,设扫到位置
注意能交换到
然后你写完了,发现样例 2 最后一个输出 66617。
问题在于,如果 set 维护)
时间复杂度
#include <cstdio>
#include <set>
using namespace std;
const int N = 100005;
typedef set < int > :: iterator iter;
char s1[N], s2[N], t1[N], t2[N];
int id1[N], id2[N];
int min(int a, int b) {
return a < b ? a : b;
}
int main() {
// freopen("in.txt", "r", stdin);
int T;
scanf("%d", &T);
for (int n; T != 0; T--) {
scanf("%d", &n);
scanf("%s", s1 + 1);
scanf("%s", s2 + 1);
scanf("%s", t1 + 1);
scanf("%s", t2 + 1);
id1[1] = id2[1] = 1;
for (int i = 2; i <= n; i++) {
if (t1[i] == '1' && t1[i - 1] == '1') {
id1[i] = id1[i - 1];
} else {
id1[i] = id1[i - 1] + 1;
}
if (t2[i] == '1' && t2[i - 1] == '1') {
id2[i] = id2[i - 1];
} else {
id2[i] = id2[i - 1] + 1;
}
}
set < int > pos01, pos10;
int ans = 0, last1 = 1, last2 = 1;
for (int i = 1; i <= n; i++) {
// pos01, pos10 至多一个非空.
if (s1[i] == s2[i]) {
ans++;
if (s1[i] == '0') {
if (!pos01.empty()) {
iter it = pos01.lower_bound(last2);
if (it != pos01.end() && it == pos01.begin()) {
pos01.erase(it);
pos01.insert(i);
}
} else if (!pos10.empty()) {
iter it = pos10.lower_bound(last1);
if (it != pos10.end() && it == pos10.begin()) {
pos10.erase(it);
pos10.insert(i);
}
}
} else {
if (!pos10.empty()) {
iter it = pos10.lower_bound(last2);
if (it != pos10.end()) {
pos10.erase(it);
pos10.insert(i);
}
} else if (!pos01.empty()) {
iter it = pos01.lower_bound(last1);
if (it != pos01.end()) {
pos01.erase(it);
pos01.insert(i);
}
}
}
} else {
if (s1[i] == '0') {
pos01.insert(i);
} else {
pos10.insert(i);
}
}
while (!pos01.empty() && !pos10.empty()) {
pos01.erase(pos01.begin());
pos10.erase(pos10.begin());
ans += 2;
}
if (id1[i] != id1[i + 1]) {
last1 = i + 1;
}
if (id2[i] != id2[i + 1]) {
last2 = i + 1;
}
int last = min(last1, last2);
while (!pos01.empty() && *pos01.begin() < last) {
pos01.erase(pos01.begin());
}
while (!pos10.empty() && *pos10.begin() < last) {
pos10.erase(pos10.begin());
}
}
printf("%d\n", ans);
}
return 0;
}
诸位,省选再见。