跳到正文

题解

Codeforces Round 1019 (Div. 2) B

__Potata__约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年4月26日
收录
2025年12月12日
更新
2026年11月22日
篇幅
约 4 分钟
题目
CF2103B

版本

  1. v2当前
  2. v1

CF2103B Binary Typewriter

题意

由题意,一个字符串的成本是打出其的操作次数。

而操作次数由两种操作组成,其一是打字,其二是移动。

前者对成本的贡献固定,为字符串长度 nn。

而后者可以通过翻转子串来降低对代价的贡献,故我们考虑一个翻转的方式,使得移动手指的次数更少,进而使得字符串的代价更小。


分析

设字符串为 SS。

我们在打出某字符前,做出移动手指的操作,当且仅当目前手指所在字符与将要打出的字符不相等。

形式化地,移动手指的次数 tt 实际为 Si≠Si−1 (i∈(1,n])S_{i} \neq S_{i - 1}\ (i \in (1, n]) 中 ii 的取值个数。

不难想到,如果翻转的子串是 [l,r][l, r],那么对于 i∈(l,r]i \in (l, r] 且 Si≠Si−1S_i \neq S_{i - 1} 在翻转前后的取值个数不变。

可以影响到的是 Sl=?Sl−1S_l \overset{?}{=} S_{l - 1} 和 Sr=?Sr+1S_r \overset{?}{=} S_{r + 1} 这两组。


细节

事实上,我们记 S={i ∣ i∈(1,n), Si−1≠Si}S = \{i\ |\ i \in (1, n),\ S_{i - 1} \neq S_i \} 为 ii 的 tt 个取值。

且设 S={S1,S2…St}S = \{S_1, S_2 \dots S_{t} \} 其影响范围由 tt 决定:

  • t≤2t \leq 2,代价为 n+t−1n + t - 1;
  • t=3t = 3,代价为 n+t−2n + t - 2;
  • t>3t > 3,代价为 n+t−3n + t - 3。

证明:

t=1t = 1,则翻转对代价的影响非负,故取 00,代价为 nn。

t=2t = 2,则有 S2=S1+1S_2 = S_1 + 1,根据 SS 的定义,不难得到 S[S1−1,S2+1]S_{[{\color{red}{S_1}} - 1, {\color{blue}{S_2}} + 1]} 形如 {a,b,a,a}\{a, {\color{red}{b}}, {\color{blue}{a}}, a\}。

也即 SS 由若干 aa 与 若干个连续的 bb 组成。a,b∈{0, 1}, a≠ba, b \in \{\texttt{0},\ \texttt{1}\},\ a \neq b。 此时令 l=S1; r=nl = S_1;\ r = n 将连续的 bb 翻转至 SS 的末尾。代价为 n+1n + 1。

t=3t = 3,可以推出 SS 形如 {a,a,…b‾,…b,a‾,…,b‾}\{{\color{red}a, a, \dots} {\color{blue}\underline{b}, \dots b}, {\color{red}\underline{a}, \dots,} {\color{blue} \underline{b}}\}:其中 SS 中的元素已用下划线标出。

令 l=S1; r=S3−1l = S_1;\ r = S_3 - 1,将会得到总代价为 n+1n + 1。

t>3t > 3,令 l=S1; r=St−1l = S_1;\ r = S_t - 1,总代价为 n+t−3n + t - 3。


实现

题干中表明,你的手最初放在 0\texttt{0} 上,故我们令 S0=0S_0 = \texttt{0}。

先在 i∈[1,n]i \in [1, n] 中找符合 Si≠Si−1S_i \neq S_{i - 1} 的取值个数(tt)。

然后再通过上面的公式计算即可。

C++
#include<iostream>
#include<algorithm>
#include<string>

using namespace std;

int q;
int n;
string str;

void solve()
{
	int cnt = 1;

	cin >> n;
	cin >> str;
	str = '0' + str;

	for (int i = 1; i <= n; i++)
		cnt += (str[i] != str[i - 1]);

	int ans;
	if (cnt < 3)
		ans = n + cnt - 1;
	else if (cnt == 3)
		ans = n + cnt - 2;
	else
		ans = n + cnt - 3;

	cout << ans << '\n';
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> q;

	while (q--)
		solve();

	return 0;
}
原文