Basic exercises-the perfect price and the cost of exercises
Problem description
A return string is a special string that reads from left to right and from right to left. Xiao Long believes that the reply string is perfect. Now, I will give you a string. It is not necessarily a return string. Please calculate the minimum number of exchanges to make the string a perfect return string.
Two adjacent characters are exchanged.
For example, mamad
First switching ad: mamda
Second exchange md: madma
The third ma exchange: madam (reply! Perfect !)
Input Format
The first line is an integer N, indicating the length of the subsequent string (N <= 8000)
The second line is a string with a length of N. It only contains lowercase letters.
Output Format
If possible, the minimum number of exchanges is output.
Otherwise, output Impossible.
Sample Input
5
Mamad
Sample output
3
#include <cstdio> #include <cstdlib> int main() { #ifdef LOCAL freopen("input2.txt", "r", stdin); #endif int n, flag = 0, ans = 0; char *str; scanf("%d", &n); str = (char*)malloc(n * sizeof(char)); scanf("%s", str); int j = n - 1, p = 0; for(int i = 0; i < j; i++) { for(int k = j; k >= 0; k--) { if(k == i) { flag++; if(n % 2 == 0 || flag > 1) { printf("Impossible\n"); return 0; } p = n/2 - i; break; } else if(str[k] == str[i]) { ans += j - k; // printf("ans = %d\n", ans); for(int f = k; f < j; f++) { str[f] = str[f + 1]; } str[j] = str[i]; j--; break; } } } printf("%d\n", ans + p); return 0; }