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;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章