题解:P14161 [ICPC 2022 Nanjing R] 完美回文
题目分析
有一个长度为
我们可以修改字符串中的任意字符,求将给定字符串变成完美回文的最少修改次数。
我们引入循环移位为旋转
关键信息ℹ️:
- 原字符串必须是回文(旋转0次的情况)
- 旋转1次后也必须是回文
- 这两个条件组合起来,会强制要求所有相邻字符都相同
得出结论完美回文必须所有字符都相同
所以 最少修改次数 = 总长度 - 出现最多的字符次数
解释样例
2
abcb
xxx
推导一个abcb
- 长度 = 4
- 字符统计: a:1, b:2, c:1
- 最多出现: b (2次)
- 修改次数 = 4 - 2 = 2
- 结果: 把a和c改为b,得到"bbbb"
推导第二个xxx
- 长度 = 3
- 字符统计: x:3
- 最多出现: x (3次)
- 修改次数 = 3 - 3 = 0
- 结果: 已经是完美回文,无需修改
AC代码 AC记录
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main() {
//ios::sync_with_stdio(false);
//cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
string s;
cin >> s;
array<int, 26> count{}; //统计26个字母出现的次数
int max_count = 0; // 记录最大出现次数
for (char c : s) {
int idx = c - 'a';
count[idx]++;
if (count[idx] > max_count) {
max_count = count[idx];
}
}
cout << s.length() - max_count << '\n';
}
return 0;
}
另一种map统计 AC记录
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
//ios::sync_with_stdio(false);
//cin.tie(nullptr);
int T;
cin >> T;
while (T--) {
string s;
cin >> s;
map<char, int> count;
int max_count = 0;
for (char c : s) {
count[c]++;
if (count[c] > max_count) {
max_count = count[c];
}
}
cout << s.length() - max_count << '\n';
}
return 0;
}