Basic exercises-the perfect price and the cost of exercises

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.