题解:P14161 [ICPC 2022 Nanjing R] 完美回文
kangkangliu · · 题解
这是本蒟蒻的第一篇题解,请各位大佬多关照关照。
简要题意:
给定长度为 n 的字符串 s,求出所有正整数 d 满足:将 s 左移 d 次后获得的字符串是一个回文串,就是完美回文串。
例:s = “abcd”,d = 2,那得到的字符串就是 “cdab”。
我的想法:
只有全是一样的或交替间隔的字符串才是完美回文串,那就可以写了。
Code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int t;
string s; //定义,懂得都懂
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0); //加个速,没毛病吧
cin >> t;
while(t--){
cin >> s; //输入
int len = s.size(); //求总长
vector<int>cnt(26, 0); //vector定义,存26个字母出现的个数
for(char c : s)cnt[c - 'a']++; //循环,这里表示用c遍历整个字符串里的字符
int maxn = *max_element(cnt.begin(), cnt.end()); //*max_element(cnt.begin(), cnt.end())表示求整个vector里出现的最大值
int ans1 = len - maxn; //用总长减去出现最多次的字母的个数就是方法一需要变换的次数
if(len % 2 == 0){ //交替变换得是偶数串
int max1 = 0, max2 = 0;
for(int i = 0; i < 26; i++){ //打擂求26个字母出现的最大值和次大值
if(cnt[i] > max1){ //如果又有了比最大值还大的数,就把最大值付上新值,次大值附上最大值
max2 = max1;
max1 = cnt[i];
}else if(cnt[i] > max2)max2 = cnt[i]; //大于次大值就也付上新值
}
int ans2 = len - max(max1, max2); //因为有间隔,所以要求两个值一块用,然后求出值来
ans1 = min(ans1, ans2); //最后打个擂
}
cout << ans1 << "\n"; //输出
}
return 0; //好习惯
}
AC Code
希望各位管理员大大能让我通过
~QWQ~