Codeforces Round 1019 (Div. 2) B
__Potata__
·
·
题解
CF2103B Binary Typewriter
题意
由题意,一个字符串的成本是打出其的操作次数。
而操作次数由两种操作组成,其一是打字,其二是移动。
前者对成本的贡献固定,为字符串长度 n。
而后者可以通过翻转子串来降低对代价的贡献,故我们考虑一个翻转的方式,使得移动手指的次数更少,进而使得字符串的代价更小。
分析
设字符串为 S。
我们在打出某字符前,做出移动手指的操作,当且仅当目前手指所在字符与将要打出的字符不相等。
形式化地,移动手指的次数 t 实际为 S_{i} \neq S_{i - 1}\ (i \in (1, n]) 中 i 的取值个数。
不难想到,如果翻转的子串是 [l, r],那么对于 i \in (l, r] 且 S_i \neq S_{i - 1} 在翻转前后的取值个数不变。
可以影响到的是 S_l \overset{?}{=} S_{l - 1} 和 S_r \overset{?}{=} S_{r + 1} 这两组。
细节
事实上,我们记 S = \{i\ |\ i \in (1, n),\ S_{i - 1} \neq S_i \} 为 i 的 t 个取值。
且设 S = \{S_1, S_2 \dots S_{t} \} 其影响范围由 t 决定:
证明:
$t = 2$,则有 $S_2 = S_1 + 1$,根据 $S$ 的定义,不难得到 $S_{[{\color{red}{S_1}} - 1, {\color{blue}{S_2}} + 1]}$ 形如 $\{a, {\color{red}{b}}, {\color{blue}{a}}, a\}$。
也即 $S$ 由若干 $a$ 与 若干个连续的 $b$ 组成。$a, b \in \{\texttt{0},\ \texttt{1}\},\ a \neq b$。
此时令 $l = S_1;\ r = n$ 将连续的 $b$ 翻转至 $S$ 的末尾。代价为 $n + 1$。
$t = 3$,可以推出 $S$ 形如 $\{{\color{red}a, a, \dots} {\color{blue}\underline{b}, \dots b}, {\color{red}\underline{a}, \dots,} {\color{blue} \underline{b}}\}$:其中 $S$ 中的元素已用下划线标出。
令 $l = S_1;\ r = S_3 - 1$,将会得到总代价为 $n + 1$。
$t > 3$,令 $l = S_1;\ r = S_t - 1$,总代价为 $n + t - 3$。
---
### 实现
题干中表明,你的手最初放在 $\texttt{0}$ 上,故我们令 $S_0 = \texttt{0}$。
先在 $i \in [1, n]$ 中找符合 $S_i \neq S_{i - 1}$ 的取值个数($t$)。
然后再通过上面的公式计算即可。
```cpp
#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;
}
```