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
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
int a[100];//array
int main(void)
{
int t;
cin >> t;
getchar();
while(t--){
string s;
int index = 0;
getline(cin,s);
for(int i=0; i<s.length(); i++){//读入数字
if(s[i]>='0' && s[i]<='9'){
a[index] = s[i] - '0';
index++;
}
}
//sort(a,a+index);sort没什么必要了
if(index == 2){
cout << a[1] - a[0] << endl;
continue;
}
int minx = 1e9;
int mid = index / 2;
while(next_permutation(a,a+index)){
int sum1 = 0;
int sum2 = 0;
if(a[0] == 0){
continue;
}
if(a[mid]){//啊~差值最小,是分的越平均越好,数的位数不能相差过大
for(int i=0; i<mid; i++){
sum1 = sum1 * 10 + a[i];
}
for(int i=mid; i<index; i++){
sum2 = sum2 * 10 + a[i];
}
int temp = abs(sum1 - sum2);
if(minx > temp){
minx = temp;
}
}
}
cout << minx << endl;
}
return 0;
}
/*题意
给定一堆数,组成两个数,使得这两个数的绝对差最小
*/
//next_permutation全排列函数

本文探讨了一道算法题目,即如何从一组不重复的十进制数字中选择子集,形成两组整数,使这两组整数的绝对差最小。通过全排列和条件判断,实现了对输入数字的有效处理,最终输出最小的绝对差。
1177

被折叠的 条评论
为什么被折叠?



