POJ:2718 Smallest Difference(暴力枚举)

来源:互联网 发布:熊猫tv直播软件 编辑:程序博客网 时间:2024/05/21 17:04
Smallest Difference
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 10416 Accepted: 2845

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

10 1 2 4 6 7

Sample Output

28

Source

Rocky Mountain 2005

题目大意:给你一些数字,这些数字都是0~9的数,且只会出现一次,让你随意组合这些数,组合成两个数,使得两数之差的绝对值最小,输出最小差的绝对值。(组合出的数的前导不能是0)
解题思路:求两数之差的最小值,如果所给数字的个数为偶数,那么肯定是n/2位的一个数减去n/2位的一个数所得的差才能尽量少,如果是奇数个数字,比如5个数字,那么结果肯定是一个三位数与一个二位数之差,用next_permutation函数枚举这些组合,然后更新结果即可。
代码如下:
#include <cstdio>#include <cstring>#include <cmath> #include <algorithm>using namespace std;#define MAX 0x3f3f3f3fint a[15];int ans,n,mid;void slove(){ans=MAX;sort(a,a+n);mid=(n+1)/2;while(a[0]==0)//把排列组合跑到a[0]不为0的那种,即第一个数x的前导一定不为0了 {next_permutation(a,a+n);}do{if(a[mid]!=0)//如果第二个数的前导也不为0 {int x=a[0],y=a[mid];            for(int i=1;i<mid;i++)            {            x=x*10+a[i];}            for(int i=mid+1;i<n;i++)            {            y=y*10+a[i];}            if(ans>abs(x-y))            {            ans=abs(x-y);}}}while(next_permutation(a,a+n));printf("%d\n",ans);}int main(){int t;char c;scanf("%d",&t);getchar();//得放到这里,不能放到while循环内部,否则会出现第二组数据答案不照,不知道什么原理 while(t--){memset(a,0,sizeof(a));n=0;while((c=getchar())!='\n')//新学的输入,也可以用gets()获得一个含空格的字符串,扫一遍放入数字数组也行         {            if(c!=' ')                a[n++]=c-'0';        }if(n==2){ans=abs(a[0]-a[1]);printf("%d\n",ans);continue;}else{slove();}}return 0;} 


0 0
原创粉丝点击