POJ:2718 Smallest Difference(暴力枚舉)

Smallest Difference
Time Limit: 1000MS   Memory Limit: 65536K
Total 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

1
0 1 2 4 6 7

Sample Output

28

Source


題目大意:給你一些數字,這些數字都是0~9的數,且只會出現一次,讓你隨意組合這些數,組合成兩個數,使得兩數之差的絕對值最小,輸出最小差的絕對值。(組合出的數的前導不能是0)
解題思路:求兩數之差的最小值,如果所給數字的個數爲偶數,那麼肯定是n/2位的一個數減去n/2位的一個數所得的差才能儘量少,如果是奇數個數字,比如5個數字,那麼結果肯定是一個三位數與一個二位數之差,用next_permutation函數枚舉這些組合,然後更新結果即可。
代碼如下:
#include <cstdio>
#include <cstring>
#include <cmath> 
#include <algorithm>
using namespace std;
#define MAX 0x3f3f3f3f
int 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;
} 


發佈了277 篇原創文章 · 獲贊 20 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章