Smallest Difference--POJ2718

[C++]Smallest Difference

Smallest Difference:
给你一些数字(单个),不会重复出现且从小到大。他们可以组成两个各个位上的数字均不一样的数,如 0, 1, 2, 4, 6 ,7可以组成10 和 2467,但最小的差值由204和176组成,差值为28,这题就是求最小的差值。

输入格式:
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.
输出格式:
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.

输入:
1
0 1 2 4 6 7
输出:
28

**解题思路:**要组成最小差值,那么两个数的长度应该是最接近的,所以从中间mid断开分成两个整数,然后求差值。用全排列排出所有情况,找出最小值。
需要注意的是当只有两个数时,直接两个数相减就可以了。

AC代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<sstream>
using namespace std;

const int INF = 99999999;

int n;
int mp[11]; 

int main(){
	
	cin>>n;
	while(n--){
		int a;
		int k = 0;
		while(true){
			cin>>a;
			mp[k++] = a;
			if(getchar() == '\n')
				break;
		}
		int minn = INF;
		if(k == 2){
			cout<<abs(mp[0] - mp[1])<<endl;
			continue;
		}
		int j = k / 2;
		do{
			int n1 = 0, n2 = 0;
			if(mp[0] == 0 || mp[j] == 0)
				continue;
			for(int i = 0; i<k; i++){
				if(i < j)
					n1 = n1 * 10 + mp[i];
				else
					n2 = n2 * 10 + mp[i];
			}
			minn = min(minn, abs(n1-n2));
		}while(next_permutation(mp, mp+k));
		
		cout<<minn<<endl;
	}
	
	
	return 0;
} 
发布了63 篇原创文章 · 获赞 8 · 访问量 7184

猜你喜欢

转载自blog.csdn.net/s1547156325/article/details/104992611