POJ 2718 穷举

题意:给定一组数字,如0, 1, 2, 4, 6, 7,用这些数字组成两个数,并使这两个数之差最小。求这个最小差。在这个例子上,就是204和176,差为28。

分析:首先可以想到,这两个数必定是用各一半数量的数字组成的数,如给出6个数,把这6个数分为两组,每组3个,这样组成的数字的差必定比其他方式小。接下来的任务就是穷举所有可能出现的组合,并求出最小差。在这里可以使用STL的next_permutation函数来求给定这组数字的所有排列,并将其分为两组组成数字,然后记录最小差。需要注意第一个数位不能为0。

 1 /*
 2 input:
 3 1
 4 0 1 2 4 6 7
 5 output:
 6 28
 7 */
 8 #include <cstdio>
 9 #include <cstring>
10 #include <algorithm>
11 #include <cstdlib>
12 
13 using namespace std;
14 
15 const int INF = 100000000;
16 
17 //输入
18 int n;
19 int a[10];
20 
21 int num(int i, int j){
22     //从数组恢复数字
23     int x = 0;
24     for(int k = i; k < j; k ++){
25         x *= 10;
26         x += a[k];
27     }
28     return x;
29 }
30 
31 void solve(){
32     //初始化
33     int ans = INF;                    //结果
34     int k = n / 2;                    //从n个数中挑出n/2个
35     do{
36         if(a[0] == 0 || a[k] == 0)continue;
37 
38         int x = num(0, k), y = num(k, n);
39         ans = min(ans, abs(x - y));
40     }while(next_permutation(a, a + n));
41     //特判包含0的两元素数组
42     if(n == 2)
43         ans = abs(a[0] - a[1]);
44     printf("%d
", ans);
45 }
46 
47 int main(int argc, char const *argv[]){
48 
49     int T;
50     scanf("%d", &T);
51     getchar();
52     while(T --){
53         char c;
54         n = 0;
55         while((c = getchar()) != '
'){
56             if(c != ' '){
57                 a[n ++] = c - '0';
58             }
59         }
60         solve();
61     }
62 
63     return 0;
64 }
原文地址:https://www.cnblogs.com/7hat/p/3599931.html