Basic exercises - the perfect price


title: basic exercises perfect price
categories:

  • ACM
  • Palindrome
    tags:
  • Moving to the shortest palindrome
    date: 2020-03-14 17:59:56

Note that exchange is adjacent interchangeable, each treatment range is [i, j], k = j, k> = i, k-. J and i look forward from the same characters found on k, j exchange, record the number of exchanges, j-, i ++; could not find it is determined that the total number of parity, even impossible to directly output, odd then make a mark (as may allow a total number of characters is odd unpaired, but the character to be in the middle), and i is moved to the record number of intermediate steps (note that only records not move, as will be moved again disrupted), i ++, continued from a look at, if there is a face can not be found, can not be directly output

problem

Questions basic exercises perfect price

By submitting this question

Resource constraints

Time limit: 1.0s Memory Limit: 512.0MB

Problem Description

Palindrome string, a special character string that is read from left to right and right to left to read the same. Little cloudy believes is the perfect palindrome string. You are given a string, it is not necessarily a palindrome, you calculate the minimum number of exchanges so that the string into a perfect palindrome string.
  The definition of exchange is: swap two adjacent characters
  such as mamad
  first exchange ad: mamda
  second exchange md: madma
  third exchange ma: madam (palindromes perfect!!)

Input Format

The first row is an integer N, the next length of the string (N <= 8000)
  The second line is a string of lowercase letters contain N.

Output Format

If possible, the output of the minimum number of exchanges.
  Otherwise, output Impossible

Sample input

5
mamad

Sample Output

3

algorithm

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main(){	
	int n;
	char s[8001];
	cin>>n>>s;
	int j=n-1,sum=0;
	bool flag=0;
	for(int i=0;i<=j;i++)
	{
		for(int k=j;k>=i;k--)
		{
			if(i==k)
			{
				if(flag||(n&1)==0)
				{
				cout << "Impossible";
                    return 0;
				}
				flag=1;
				sum+=n/2-i;
			}
			else if(s[i]==s[k])
			{
				for(int i=k;i<=j-1;i++)
				{
					swap(s[i],s[i+1]);
					sum++;
				}
				j--;
				break;
			}
		}
	}
	cout<<sum;
}
Published 43 original articles · won praise 1 · views 915

Guess you like

Origin blog.csdn.net/qq_43985303/article/details/104865596