Smallest Difference(POJ 2718)

时间:2022-09-22 15:24:19
Smallest Difference
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6740   Accepted: 1837

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

Source

 
给定一个数字序列,将其分为两部分,求差绝对值的最小值;
next_permutation()即可,但需要判断首元素是否为0
 #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int a[];
int main()
{
int T;
scanf("%d",&T);
getchar();
while(T--)
{
int temp;
int n=,i,Min=;
while((temp=getchar())!='\n')
{
if(temp!=' ')
a[n++]=temp-'';
}
sort(a,a+n);
/* for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;*/
if(n==&&a[]==)
{
cout<<a[]<<endl;
continue;
}
do{
int num1=,num2=,m;
if(a[]==||a[n/]==)
continue;
for(i=;i<n/;i++)
num1=num1*+a[i];
for(;i<n;i++)
num2=num2*+a[i];
Min=min(Min,abs(num1-num2));
//cout<<num1<<" "<<num2<<" "<<abs(num1-num2)<<" "<<Min<<endl;
}while(next_permutation(a,a+n));
printf("%d\n",Min);
}
}