POJ 2718 Smallest Difference(最小差)

时间:2022-02-08 14:42:39


POJ 2718 Smallest Difference最小差

Time Limit: 1000MS    Memory Limit: 65536K

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.

给定若干位十进制数,你可以通过选择一个非空子集并以某种顺序构建一个数。剩余元素可以用相同规则构建第二个数。除非构造的数恰好为0,否则不能以0打头。

举例来说,给定数字0,,,,6与7,你可以写出10和2467。当然写法多样:210和764,204和176,等等。最后一对数差的绝对值为28,实际上没有其他对拥有更小的差。

CN

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.

输入第一行的数表示随后测试用例的数量。

对于每组测试用例,有一行至少两个不超过10的十进制数字。(十进制数字为0,,…,)每行输入中均无重复的数字。数字为升序给出,相隔恰好一个空格。

CN

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.

对于每组测试用例,输出一个以上述规则可获得的最小的差的绝对值在一行。

CN

Sample Input - 输入样例

1
0 1 2 4 6 7

Sample Output - 输出样例

28

题解

  对给定的数字任意组合,不得出现前导0,因此直接把划分位置选定为中间。枚举情况即可。

代码 C++

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
char data[];
int rd(int l, int r){//[l, r]
int opt = ;
for (; l <= r; ++l) opt = opt * + data[l] - '';
return opt;
}
int main(){
int t, i, j, mid, l, r, opt;
scanf("%d ", &t);
while (t--){
memset(data, , sizeof data); opt = 0x7FFFFFFF;
gets(data);
for (i = , j = ; data[i - ]; ++i, j += ) data[i] = data[j];
i -= ; mid = i >> ;
do {
if (mid && data[] == '') continue;
if (i - mid - && data[mid + ] == '') continue;
l = rd(, mid); r = rd(mid + , i);
opt = std::min(opt, std::abs(l - r));
} while (std::next_permutation(data, data + i + ));
printf("%d\n", opt);
}
return ;
}