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
", solve());
    return 0;
}
原文地址:https://www.cnblogs.com/yxwkf/p/5262189.html