POJ2718 Smallest Difference

POJ2718 Smallest Difference

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
2
1
0 1 2 4 6 7

Sample Output

1
28

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <cstdio>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;

const int INF = 1e+9;
int n, a[10], d[2];

int a2i(int x, int y);
void solve();

int main() {
int T;
scanf("%d", &T);
getchar();
while (T--) {
string str;
getline(cin, str);
stringstream ss(str);
n = 0;
while (ss >> a[n]) {
++n;
}
solve();
}
return 0;
}

void solve() {
int ans = INF;
do {
int x, y;
x = a2i(0, n/2);
y = a2i(n/2, n);
if (x != -1 && y != -1) {
ans = min(ans, abs(x-y));
}
} while(next_permutation(a, a+n));
printf("%d\n", ans);
}

int a2i(int x, int y) {
int res = 0;
if (a[x] == 0 && y - x > 1) {
return -1; // starts with 0
}
for (int i = x; i < y; ++i) {
res = 10 * res + a[i];
}
return res;
}

Analysis

  1. 一个数字数组,分割成两个数组,求这两个数组组成的整数的差,取其中最小值。0 只能作为一位数字,即 0 开头的数字只有 0。
  2. 全排列遍历,取中间为分隔符即可。
  3. stringstream 很好用。
# POJ

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×