#C8874. Making a Palindrome with Minimum Cost
Making a Palindrome with Minimum Cost
Making a Palindrome with Minimum Cost
You are given a string s
consisting of lowercase English letters. Your task is to compute the minimum total cost required to convert the string into a palindrome.
A string is a palindrome if it reads the same backward as forward. In this problem, you can change the characters to make the string palindromic. For each pair of characters at positions i
and n-i-1
(where n
is the length of the string and 0 \le i < n/2
), if they are different, you incur a cost equal to the absolute difference of their ASCII values. Formally, the total cost is given by:
[ \text{Cost} = \sum_{i=0}^{\lfloor \frac{n}{2} \rfloor - 1} \left|\text{ord}(s[i]) - \text{ord}(s[n-i-1])\right| ]
Your goal is to compute and output this total cost.
Examples:
- For
s = "abc"
, the cost is|ord('a')-ord('c')| = |97-99| = 2
. - For
s = "abcd"
, the cost is|ord('a')-ord('d')| + |ord('b')-ord('c')| = |97-100| + |98-99| = 3 + 1 = 4
. - For
s = "racecar"
, the string is already a palindrome so the cost is 0.
inputFormat
The input consists of a single line containing a non-empty string s
of lowercase English letters.
outputFormat
Output a single integer — the minimum total cost required to convert the given string into a palindrome.
## sampleabc
2
</p>