天天看点

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 =  + ;

int N, P;
vector<int> pos;
char s[maxn];

int solve () {
    int ret = , n = N / ;;
    for (int i = ; i < n; i++) {
        int tmp = abs(s[i] - s[N-i-]);
        tmp = min(tmp,  - tmp);
        ret += tmp;
        if (tmp)
            pos.push_back(abs(i+-P) < abs(N-i-P) ? i+ : N-i);
    }
    n = pos.size();

    if (n == )
        return ret;
    sort(pos.begin(), pos.end());
    return ret + pos[n-] - pos[] + min(abs(pos[n-]-P), abs(pos[]-P));
}

int main () {
    scanf("%d%d%s", &N, &P, s);
    printf("%d\n", solve());
    return ;
}