Topic
Enter an array of positive integers, connect them together in a number, and output the smallest of all the emitted numbers. For example: input array [32,321], the output can be discharged by the minimum number is: 32132. Please give the algorithm of the problem.
Analysis
For the problem of element placement, such as A/b, we would like to find a permutation rule to determine whether we want to get a A, a, B or b,a. The minimum number of questions required to be discharged, that is, as a<b, from common sense ab<ba. Is this rule of comparison exactly right? There is a good proof in the book of the sword-point offer.
http://zhedahht.blog.163.com/blog/static/25411174200952174133707/
An effective comparison rule requires three conditions: reflexivity, symmetry, transitivity. The proof process is as follows
1. Reflexivity. That is a=a.
Apparently like Aa=aa, then a=a
2. Symmetry. That is, if a>b, then b<a.
If a<b, by the rule ab<ba, obviously ba>ab, namely B>a.
3. transitivity. That is, if a<b,b<c, then a<c
Assuming conditional a<b,b<c, it is AB<BA,BC<CB according to the rule. Suppose that the 10 powers of the a,b,c at high level are m,n,l, respectively.
Then a*10^m+b<b*10^n+a-"A * (10^m-1) <b* (10^n-1);
b*10^n+c<c*10^l+b-"b* (10^n-1) <c* (10^L-1);
So there is a * (10^m-1) <c* (10^L-1)
namely a*10^m+c<c*10^l+a-"Ac<ca
So there's a<c.
We can also prove this rule with a discussion of the situation. For A/b in an array, the emitted number is either a in front of B or a in front of a. Assume that other elements have been ranked as a minimum of XXX. There are three different situations:
http://blog.csdn.net/wuzhekai1985/article/details/6704902
1. abxxx
Apparently, if ab<ba,abxxx<baxxx
2. Xxxab
Apparently, if ab<ba,abxxx<baxxx
3. Axxxb
We regard the middle part as C, then there is ACB. We know Ab<ba and need to prove ACB<BCA. Assuming that the a,c,b are m,n,l, respectively.
If ACB>BCA, then a*10^m+c*10^n+b>b*10^l+c*10^n+a, both sides simultaneously reduce c*10^n-"a*10^m+b>b*10^l+a namely Ab>ba and the known contradiction. Thus, the ACB<BCA can be proven
Code
1 Const intmax_digits=Ten;2 intcatstr_max_len=2*max_digits+1;3 Char* catstr1=New Char[Catstr_max_len];4 Char* catstr2=New Char[Catstr_max_len];5 intCompConst voidAConst void*b)6 {7sprintf (CATSTR1,"%d%d",*(int*) a,* (int*) b);8 9sprintf (CATSTR2,"%d%d",*(int*) b,* (int*) a);Ten One returnstrcmp (CATSTR1,CATSTR2); A } - voidPrintminnumber (intNumbers[],intlen) - { the if(!numbers| | len<=0) - { - ThrowStd::exception ("Invalid input."); - } + - //char* strnum=new char[len*max_digits]; +Qsort (Numbers,len,sizeof(int*), comp); A at for(intI=0; i<len;i++) - { -cout<<Numbers[i]; - } -cout<<Endl; -}
Algorithm 19 to arrange the array into the smallest number