Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 ≤ i ≤ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).
When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.
Initially, the text cursor is at position p.
Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
The first line contains two space-separated integers n (1 ≤ n ≤ 105) and p (1 ≤ p ≤ n), the length of Nam's string and the initial position of the text cursor.
The next line contains n lowercase characters of Nam's string.
Print the minimum number of presses needed to change string into a palindrome.
由于要得到回文串,最好在p所在的那个半边改就好了,并求得半边里最小的l(1<=l<=p)和最大的r使得s[l]!=s[n-l+1] && s[r]!= s[n-r+1]
那么最优解无非是p-l,l-r或者p-r,r-l中的一种
注意考虑边界情况,比如l和r不存在的情况
#include <bits/stdc++.h> using namespace std; typedef long long LL; #define SIZE 100005 string s; int n,p; int res = 0; int dist(char ch,char ch2){ if (ch > ch2){ swap(ch,ch2); } return min(ch2 - ch,ch - ch2 + 26); } int main() { // freopen("test.in","r",stdin); ios::sync_with_stdio(false); cin >> n >> p; cin >> s; // cout << dist('b','z') << endl; if (p > n/2){ p = n - p + 1; for (int i=0;i<n/2;i++){ swap(s[i],s[n-1-i]); } } p = p-1; int l = -1,r = -1; for (int i=0;i<=p;i++){ if (s[i] != s[n-1-i]){ l = i; break; } } for (int i=p;i<n/2;i++){ if (s[i] != s[n-i-1]){ r = i; } } // cout << l << r << endl; if (l == -1){ if (r == -1){ cout << 0; return 0; } else { res = r - p; for (int i=p+1;i<=r;i++){ res += dist(s[i],s[n-i-1]); } cout << res; return 0; } } else if (r == -1){ res = p - l; for (int i=l;i<p;i++){ res += dist(s[i],s[n-i-1]); } cout << res; return 0; } else { res = min(p-l,r-p); res += r-l; for (int i=l;i<=r;i++){ res += dist(s[i],s[n-i-1]); } cout << res; return 0; } return 0; }