跳到正文

个人记录

P11361 [NOIP2024] 编辑字符串 题解 | 趣味贪心

cancan123456约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年11月30日
收录
2025年12月12日
更新
2026年10月23日
篇幅
约 5 分钟

版本

  1. v1当前

先说说考场思路(注意是错的)。

首先交换可以看作一段区间内重排,这样 t=0t=0 的位置可以看作在这个长 11 的区间内重排。

考虑贪心,维护能交换到 ii 的不匹配的位置,有两种类型 s1,i=0,s2,i=1s_{1,i}=0,s_{2,i}=1 或者 s1,i=1,s2,i=0s_{1,i}=1,s_{2,i}=0,简称为 0101 型位置和 1010 型位置。

从头到尾扫一遍序列,设扫到位置 ii,如果 s1,i=s2,is_{1,i}=s_{2,i} 那么令答案加一。否则,如果是 0101 型那么看一眼前面有没有 1010 型位置,如果有就交换一下,如果没有就加入进 0101 型位置。

注意能交换到 ii 的位置可以快速维护而且随着 ii 增加这个位置也增加,所以开个队列维护一下就好。

然后你写完了,发现样例 2 最后一个输出 66617。

问题在于,如果 s1,i=s2,is_{1,i}=s_{2,i}(假设都等于 00),那么可以用这个位置把最靠前的能交换的(用 set 维护)0101 型位置或者 1010 型位置换到后面来,而不是什么都不做,然后分类讨论一下就对了。

时间复杂度 O(Tnlog⁡n)O(Tn\log n),通过了所有样例。

C++
#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;
}

诸位,省选再见。

原文