POJ 2718 Smallest Difference

来源:互联网 发布:mysql 创建存储过程 编辑:程序博客网 时间:2024/06/05 09:25

Smallest Difference

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 12711 Accepted: 3448

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

Thinking 暴力枚举就好了,因为一共就10个数字。我还是遇到了来自输入和循环条件重置的错误,人丑就是要多写代码。另外注意一下只有2个数字输入的特殊情况。

#include<cstdio>#include<algorithm>#include<cmath>#include<cstring>#include<iostream>using namespace std;const int maxn = 11;int line[maxn];int kase;char c;int sum1 = 0, sum2 = 0, minimum = 0x3f3f3f3f;int main() {    scanf("%d", &kase);    getchar();    while (kase--) {        int index = 0;        while ((c = getchar()) != '\n') {            if (c != ' ')                line[index++] = c - '0';        }        if (index == 2) {            printf("%d\n", abs(line[1] - line[0]));        }        else {            do {                if (line[0] == 0 || line[index/2] == 0)                    continue;                for (int i = 0; i < index / 2; i++)                    sum1 = sum1 * 10 + line[i];                for (int j = index / 2; j < index; j++)                    sum2 = sum2 * 10 + line[j];                minimum = min(minimum, abs(sum1 - sum2));                sum1 = 0;                sum2 = 0;            } while (next_permutation(line, line + index));            printf("%d\n", minimum);            sum1 = sum2 = 0;            minimum = 0x3f3f3f3f;        }    }    return 0;}
原创粉丝点击