http://poj.org/problem?id=2718
从一些数里面选择一个子集组成一个数,余下的数组成另外一个数,(数不能以0开头)问两个数的差的绝对值最小是多少!
不管是奇数还是偶数,要想绝对值最小,那么两个数的位数就要尽量接近,所以每一个数的位数都是n/2,枚举这些数的全排列,然后去找这个最小值。
注意的是直接枚举会超时,需要剪枝。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue> #define CL(arr, val) memset(arr, val, sizeof(arr)) #define ll long long
#define inf 0x7f7f7f7f
#define lc l,m,rt<<1
#define rc m + 1,r,rt<<1|1
#define pi acos(-1.0) #define L(x) (x) << 1
#define R(x) (x) << 1 | 1
#define MID(l, r) (l + r) >> 1
#define Min(x, y) (x) < (y) ? (x) : (y)
#define Max(x, y) (x) < (y) ? (y) : (x)
#define E(x) (1 << (x))
#define iabs(x) (x) < 0 ? -(x) : (x)
#define OUT(x) printf("%I64d\n", x)
#define lowbit(x) (x)&(-x)
#define Read() freopen("a.txt", "r", stdin)
#define Write() freopen("b.txt", "w", stdout);
#define maxn 1000000000
#define N 1010
using namespace std; int main()
{
//Read();
//Write()
int t;
int f[],n,minn;
string s;
scanf("%d",&t);
getchar();
while(t--)
{
getline(cin,s);
n=;
for(int i=;i<s.length();i++)
{
if(s[i]>=''&&s[i]<='') f[n++]=s[i]-'';
}
// printf("%d\n",n);
// for(int i=0;i<n;i++) printf("%d ",f[i]);
if(n==) {printf("%d\n",abs(f[]-f[]));continue;}
minn=maxn;
while(f[]==) next_permutation(f,f+n); //剪枝
do
{
if(f[n/]) //剪枝
{
int x=,y=;
for(int i=;i<n/;i++) x=x*+f[i];
for(int i=n/;i<n;i++) y=y*+f[i];
minn=min(abs(x-y),minn);
}
}while(next_permutation(f,f+n));
printf("%d\n",minn);
}
return ;
}