Smallest Difference - poj2718 - 模拟

Smallest Difference

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 15916   Accepted: 4295

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

Rocky Mountain 2005

扫描二维码关注公众号,回复: 2558256 查看本文章

题意:

按从小到大的顺序排序给你不重复数,然后让你任一把这几个数分成两拨,组成两个整数,求所有情况中,两数之差绝对值的最小,注意0对于非一位数,0不能放在最前面

思路:

相差绝对值最小的两个数,一定是位数最接近的,设一共m个数,则第一个数有m/2位,第二个数有m-m/2位,这时,我们用next_permutation函数进行全排列,在排除两个数0打头的情况下,进行计算。

(全排列可以得到所有的情况,从排好的数组里取前 m/2 位做为第一个数,后 m-m/2 位做为第二个数)

(注意使用getline函数要加上头文件#include<string>不然会“

F:\temp\18923699.26683\Main.cpp(17) : error C3861: 'getline': identifier not found

”)

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
 
using namespace std;
int a[15];
int main(){
	int t;
	scanf("%d",&t);
	getchar();
	while(t--){
		string s;
	    memset(a,0,sizeof(a));
	    getline(cin,s);
	    int len=s.length(),m=0;
	    for(int i=0;i<len;i++){
	    	if(s[i]!=' '){
	    		a[m++]=s[i]-'0';
			}
		}
		int mymin=0x3f3f3f3f;
		
		do{
			int t1=0,t2=0;
			if(a[0]==0&&m/2!=1)continue;
			if(a[m/2]==0&&(m-m/2)!=1)continue;
			for(int i=0;i<m/2;i++){
				t1=t1*10+a[i];
			}
			for(int i=m/2;i<m;i++){
				t2=t2*10+a[i];
			}
			mymin=min(mymin,abs(t1-t2));
		}while(next_permutation(a,a+m));
		printf("%d\n",mymin);
	}
}

猜你喜欢

转载自blog.csdn.net/m0_37579232/article/details/81273283