1. 程式人生 > >POJ-2718

POJ-2718

ret cor algorithm total malle sam block 情況 erl

Smallest Difference
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12158 Accepted: 3306

Description

Given a number of distinct decimal digits, you can form one integer by choosing a non-empty subset of these digits and writing them in some order. The remaining digits can be written down in some order to form a second integer. Unless the resulting integer is 0, the integer may not start with the digit 0.

For example, if you are given the digits 0, 1, 2, 4, 6 and 7, you can write the pair of integers 10 and 2467. Of course, there are many ways to form such pairs of integers: 210 and 764, 204 and 176, etc. The absolute value of the difference between the integers in the last pair is 28, and it turns out that no other pair formed by the rules above can achieve a smaller difference.

Input

The first line of input contains the number of cases to follow. For each case, there is one line of input containing at least two but no more than 10 decimal digits. (The decimal digits are 0, 1, ..., 9.) No digit appears more than once in one line of the input. The digits will appear in increasing order, separated by exactly one blank space.

Output

For each test case, write on a single line the smallest absolute difference of two integers that can be written from the given digits as described by the rules above.

Sample Input

1
0 1 2 4 6 7

Sample Output

28

題意:

將所給出的所有數字排列組合生成兩個數,使其差的絕對值最小。求最小值。

貪心可做,學到了一種STL求全排列的方法:next_permutation();

AC代碼:

 1 //#include<bits/stdc++.h>
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<cmath>
 7 using namespace std;
 8 
 9 const int INF=1<<30;
10 char str[30];
11 int num[15];
12 
13 int main(){
14     int n;
15     cin>>n;
16     getchar();
17     while(n--){
18         int res=INF;
19         gets(str);//得到數列 
20         int len=strlen(str);
21         int k=0;
22         for(int i=0;i<len;i++){
23             if(str[i]>=0&&str[i]<=9){
24                 num[k++]=str[i]-0;
25             }
26         }
27         if(k==2){//如果只有兩個數的情況 
28             cout<<abs(num[0]-num[1])<<endl;
29             continue;
30         }
31         while(num[0]==0){//不能含有前導零 
32             next_permutation(num,num+k);
33         }
34         //int ans=INF;
35         do{
36             int mid=(k+1)/2;
37             if(num[mid]){//第二個數也不能有前導零 
38                 int a=0,b=0;
39                 for(int i=0;i<mid;i++){
40                     a=a*10+num[i];
41                 }
42                 for(int i=mid;i<k;i++){
43                     b=b*10+num[i];
44                 }
45                 res=min(res,abs(a-b));
46             }
47             
48         }while(next_permutation(num,num+k));
49         cout<<res<<endl;
50     }
51     return 0;
52 }

POJ-2718