Title Address
Brief test Instructions:
For several sets of numbers, each group of data is incremented by the number of 0--9, and the number of each group is indeterminate. For each set of numbers, the absolute value of the difference in the output of two numbers consisting of these numbers is minimal (each number appears and appears only once).
Thinking Analysis:
For the number of n, the absolute value of the difference can be minimized if the number of N/2 and N-N/2 is divided into two digits respectively. The two groups of numbers are all arranged in the comparison size, so that the maximum number of comparisons is (10A5) * (5A5) =10! , within an acceptable range.
Reference code:
1#include <stdio.h>2#include <cstring>3#include <iostream>4#include <algorithm>5 using namespacestd;6typedefLong Longll;7 Const intinf=0x3f3f3f3f;8 inta[ A],t,n,ans,b[ A];9 BOOLvi[ A];Ten voidCheckintx) One { A intlen=0, y=0, I; - for(i=0; i<n;i++) - { the if(!Vi[i]) -b[len++]=a[i],y=y*Ten+A[i]; - } - if(b[0]!=0|| len==1)//If there are only 1 digits, the first (i.e. the only one) can be 0 +Ans=min (Ans,abs (xy)); - while(Next_permutation (B,b+len))//full array borrowing next_permutation functions + { Ay=0; at for(i=0; i<len;i++) - { -y=y*Ten+B[i]; - } - if(b[0]!=0|| len==1) -Ans=min (Ans,abs (xy)); in } - } to voidDfsintKintAn ) + { - the if(k==n/2) * { $ check (an);Panax Notoginseng return; - } the Else + { A inti; the for(i=0; i<n;i++) + { - if(!Vi[i]) $ { $ if(a[i]==0&&k==0&&n>3)//there is only one and the situation is 0 at this time - Continue; -vi[i]=true; theDFS (k +1, an*Ten+a[i]); -vi[i]=false;Wuyi } the } - } Wu } - intMain () About { $ Chartem; - while(~SCANF ("%d", &t))//%d followed by a space can not be extra getchar read the line break - { - while(t--) A { +n=0; the while((Tem=getchar ())! ='\ n')//Note the method of reading in - { $ if(tem==' ') the Continue; thea[n++]=tem-'0'; the } theans=INF; -Memset (VI,false,sizeof(vi)); inDfs0,0); theprintf"%d\n", ans); the } About } the return 0; the}
(DFS, full array) POJ-2718 smallest difference