首页 > 代码库 > Codeforces 486C Palindrome Transformation(贪心)
Codeforces 486C Palindrome Transformation(贪心)
题目链接:Codeforces 486C Palindrome Transformation
题目大意:给定一个字符串,长度N,指针位置P,问说最少花多少步将字符串变成回文串。
解题思路:其实只要是对称位置不相同的,那么指针肯定要先移动到这里,修改字符只需要考虑两种方向哪种更优即
可。然后将所有需要到达的位置跳出来,贪心处理。
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 5;
int N, P;
vector<int> pos;
char s[maxn];
int solve () {
int ret = 0, n = N / 2;;
for (int i = 0; i < n; i++) {
int tmp = abs(s[i] - s[N-i-1]);
tmp = min(tmp, 26 - tmp);
ret += tmp;
if (tmp)
pos.push_back(abs(i+1-P) < abs(N-i-P) ? i+1 : N-i);
}
n = pos.size();
if (n == 0)
return ret;
sort(pos.begin(), pos.end());
return ret + pos[n-1] - pos[0] + min(abs(pos[n-1]-P), abs(pos[0]-P));
}
int main () {
scanf("%d%d%s", &N, &P, s);
printf("%d\n", solve());
return 0;
}
Codeforces 486C Palindrome Transformation(贪心)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。