POJ-2718 Smallest Difference

http://poj.org/problem?id=2718

从一些数里面选择一个子集组成一个数,余下的数组成另外一个数,(数不能以0开头)问两个数的差的绝对值最小是多少!

不管是奇数还是偶数,要想绝对值最小,那么两个数的位数就要尽量接近,所以每一个数的位数都是n/2,枚举这些数的全排列,然后去找这个最小值。

注意的是直接枚举会超时,需要剪枝。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <vector>
 5 #include <cstring>
 6 #include <string>
 7 #include <algorithm>
 8 #include <string>
 9 #include <set>
10 #include <functional>
11 #include <numeric>
12 #include <sstream>
13 #include <stack>
14 #include <map>
15 #include <queue>
16 
17 #define CL(arr, val)    memset(arr, val, sizeof(arr))
18 
19 #define ll long long
20 #define inf 0x7f7f7f7f
21 #define lc l,m,rt<<1
22 #define rc m + 1,r,rt<<1|1
23 #define pi acos(-1.0)
24 
25 #define L(x)    (x) << 1
26 #define R(x)    (x) << 1 | 1
27 #define MID(l, r)   (l + r) >> 1
28 #define Min(x, y)   (x) < (y) ? (x) : (y)
29 #define Max(x, y)   (x) < (y) ? (y) : (x)
30 #define E(x)        (1 << (x))
31 #define iabs(x)     (x) < 0 ? -(x) : (x)
32 #define OUT(x)  printf("%I64d
", x)
33 #define lowbit(x)   (x)&(-x)
34 #define Read()  freopen("a.txt", "r", stdin)
35 #define Write() freopen("b.txt", "w", stdout);
36 #define maxn 1000000000
37 #define N 1010
38 using namespace std;
39 
40 int main()
41 {
42    //Read();
43    //Write()
44    int t;
45    int f[15],n,minn;
46    string s;
47    scanf("%d",&t);
48    getchar();
49    while(t--)
50    {
51        getline(cin,s);
52        n=0;
53        for(int i=0;i<s.length();i++)
54        {
55            if(s[i]>='0'&&s[i]<='9') f[n++]=s[i]-'0';
56        }
57       // printf("%d
",n);
58       // for(int i=0;i<n;i++) printf("%d ",f[i]);
59        if(n==2) {printf("%d
",abs(f[0]-f[1]));continue;}
60        minn=maxn;
61        while(f[0]==0) next_permutation(f,f+n);  //剪枝
62        do
63        {
64            if(f[n/2])   //剪枝
65            {
66                int x=0,y=0;
67                for(int i=0;i<n/2;i++) x=x*10+f[i];
68                for(int i=n/2;i<n;i++) y=y*10+f[i];
69                minn=min(abs(x-y),minn);
70            }
71        }while(next_permutation(f,f+n));
72        printf("%d
",minn);
73    }
74    return 0;
75 }
原文地址:https://www.cnblogs.com/nowandforever/p/4401572.html