This topic is the programmer's 11th algorithm middleware topic.
Input a string with a length of N on the keyboard, exchange the positions of two adjacent characters, and determine whether the string can be converted into a return string after a limited number of exchanges. If yes, the number of exchanges is output, if not, "impossible" is output ".
I give the C ++ program solution of the following algorithm, but I don't know if this program can guarantee that the number of exchanges obtained can reach the optimal value, that is, the minimum number of exchanges is converted into a return string. For reference only. If you have better ideas, call me! We will study it together.
The program code is as follows:
# Include <iostream>
# Include <string>
Using namespace STD;
Class Huiwen // define a given string class
{
PRIVATE:
String S;
Int Len;
Public:
Huiwen (string STR, int len1): S (STR), Len (len1)
{}
Int panduan ();
Int count ();
};
Int main ()
{
Int rez, n = 0, NO = 0;
String S1;
Cin> N;
Cin> S1;
Huiwen A1 (S1, N );
Rez = a1.panduan ();
If (REZ = 0)
{
// Cout <"can be changed. "<Endl;
No = a1.count ();
Cout <no <Endl;
}
Else
Cout <"impossible" <Endl;
Return 0;
}
Int Huiwen: Count ()
{
Char * c = new char [Len];
Char temp_char = '';
Int I = 0, j = 0, Count = 0, NO = 0, K;
For (I = 0; I <Len; I ++)
{
* (C + I) = s [I];
// Cout <"c =" <* (C + I) <Endl;
}
* (C + Len) = '/0 ';
For (I = 0; I <= Len/2; I ++)
{
/* For (k = 0; k <Len; k ++)
{
Cout <* (C + k );
}
Cout <Endl ;*/
For (j = len-1-i; j> = I; j --)
{
If (* (C + I )! = * (C + J ))
{
Continue;
}
Else
{
// Cout <"I and j" <I <"" <j <Endl;
If (I! = J)
{
No = J;
Break;
}
Else
{
// Cout <"the search sequence number is equal to:" <I <Endl;
Return count;
}
}
}
If (I> J)
{
// Cout <"out of bounds. "<I <Endl;
Return count;
}
Temp_char = * (C + NO );
// Cout <"and" <I <"the same character appears in" <no <Endl;
For (j = no; j <len-i-1; j ++)
{
* (J + C) = * (C + J + 1 );
Count ++;
}
// Cout <"number of moves:" <count <Endl;
* (C + J) = temp_char;
}
Return count;
}
Int Huiwen: panduan ()
{
Int * A = new int [Len];
Char * B = new char [Len];
Int J, m = 0, c = 0, I, Sig = 0;
For (INT I = 0; I <S. Length (); I ++)
{
For (j = 0; j <m; j ++)
{
If (s [I] = * (B + J ))
{
Sig = 1;
Break;
}
Else
Sig = 0;
}
If (Sig = 1)
Continue;
* (B + M) = s [I];
M ++;
* (B + M) = '/0 ';
}
// Cout <"m =" <m <Endl;
For (j = 0; j <m; j ++)
{
* (A + J) = 0;
// Cout <"B =" <B [J] <Endl;
}
* (A + J) = '/0 ';
For (j = 0; j <m; j ++)
{
For (I = 0; I <S. Length (); I ++)
{
If (* (B + J) = s [I])
(* (A + J) ++;
}
}
For (j = 0; j <m; j ++)
{
// Cout <* (a + J) <Endl;
If (* (a + J) % 2 )! = 0)
C ++;
}
// Cout <"c =" <C <Endl;
If (C> 1)
Return 1; // you can change it to a text return.
Else
Return 0; // unchangeable
}