Smallest Difference
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7225 | Accepted: 1964 |
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.
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
不难想到,最优解的两个数,位数肯定位数相同或者相差一位,为了枚举所有的种类,可以直接在n 个数的全排列中进行操作,个人设定数组前n/2 个数为第一个数,其余为第二个数,首先判断是否有前导零,没有就计算两个数的和,否则就剪枝掉(个人使用的现成的函数,貌似优化的不多),不断更新计算出的最小值。
使用permutation 函数,比较方便,不过不便于操作,个人推荐手动实现dfs,这样能优化很多。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn=0x3f3f3f3f;
int num(int x[],int n)
{
int a=0,b=0;
for(int i=0;i<n/2;++i)
{
a=a*10+x[i];b=b*10+x[i+n/2];
}
if(n&1)//奇数多一位
{
b=b*10+x[n-1];
}
return abs(b-a);
}
int main()
{
int t;
scanf("%d",&t);
getchar();
while(t--)
{
int x[15]={0},cnt=0;
char ch;
while((ch=getchar())!='\n')
{
if(ch>='0'&&ch<='9')
{
x[cnt++]=ch-'0';
}
}
int ans=maxn;
do
{
if((cnt/2>1&&!x[0])||(!x[cnt/2]&&cnt-cnt/2>1))
//不是个位数就不允许首位为 0
{
continue;
}
int tp=num(x,cnt);
ans=min(ans,tp);
}while(next_permutation(x,x+cnt));
printf("%d\n",ans==maxn?0:ans);
}
return 0;
}