Codeforces Round 1014 (Div. 2) D
__Potata__
·
·
题解
CF2092D Mishkin Energizer
解析
显然在注意到 n 的数据范围时,
我们就可以考虑本题的大模拟解法了。
首先,对于每个选定的操作数 i,添加的 x 是固定的,即:
x = L\ \operatorname{xor}\ I\ \operatorname{xor}\ T\ \operatorname{xor}\ S_i\ \operatorname{xor}\ S_{i + 1}
这仅是一个计算方法,其正确性我们不难证明。
证明:
∵\ x \neq S_i;\ x \neq S_{i + 1};\ x \in \{\texttt{L},\ \texttt{I},\ \texttt{T}\}
∴\ x \in \{\texttt{L},\ \texttt{I},\ \texttt{T}\}\ - \{S_i,\ S_{i + 1}\}
又因为 S_i \neq S_{i + 1} 且 S \in \{\texttt{L},\ \texttt{I},\ \texttt{T}\}。
故 \{\{\texttt{L},\ \texttt{I},\ \texttt{T}\}\ - \{S_i,\ S_{i + 1}\}\} 中有且仅有 1 个元素。
证得:x 的取值是唯一的,且显而易见地可以通过上式计算出来。
于是对于每次操作(最坏情况下):
我们使用 O(n) 的时间复杂度遍历字符串。
每次**添加**的时间复杂度为 $O(n)$。
共 $2n$ 次操作。故时间复杂度为 $O(n^3)$。
---
### 代码
码风清奇、注释详尽。
```cpp
#include<iostream>
#include<vector>
#include<string>
#include<map>
#define potata 105
#define cal ('L' ^ 'I' ^ 'T')
using namespace std;
int q;
string str;
int n;
map<char, int> cnt;
vector<int> ans;
bool equal()
{
return (cnt['L'] == cnt['I'] && cnt['L'] == cnt['T'] && cnt['I'] == cnt['T']);
} // 判断饮料平衡
void solve()
{
cin >> n;
cin >> str;
cnt.clear();
ans.clear();
// 多测不清见祖宗
for (int i = 0; i < n; i++)
cnt[str[i]]++;
int step = 0;
while (equal() == false && step <= 2 * n) // O(2n) 次操作
{
bool flg = false;
for (int i = 0; i < str.size() - 1; i++) // O(n) 遍历
{
if (str[i] == str[i + 1])
continue; // 可行性
char ch = cal ^ str[i] ^ str[i + 1];
int Cnt = cnt[ch];
int Max = max(cnt['L'], max(cnt['I'], cnt['T']));
// 最优性
if (Cnt < Max)
{
str.insert(str.begin() + i + 1, ch); // O(n) 插入
ans.push_back(i + 1);
cnt[ch]++;
flg = true;
break;
} // 小优化
}
if (flg == false)
{
for (int i = 0; i < str.size() - 1; i++)
{
if (str[i] != str[i + 1])
{
char ch = cal ^ str[i] ^ str[i + 1];
str.insert(str.begin() + i + 1, ch);
ans.push_back(i + 1);
cnt[ch]++;
flg = true;
break;
}
}
} // 确保最优性
if (flg == false)
break; // 可行性(剪枝)
step++;
} // 上面的步骤是至多 2n 次操作的最优方案
if (equal())
{
int Ans = ans.size();
cout << Ans << '\n';
for (int i = 0; i < Ans; i++)
cout << ans[i] << '\n';
}
else
cout << -1 << '\n';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie();
cin >> q;
while (q--)
solve();
return 0;
}
```