天天看點

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 ;
}