1038. Recover the Smallest Number (30)

1038. Recover the Smallest Number (30)

時間限制
400 ms
內存限制
65536 kB
代碼長度限制
16000 B
判題程序
Standard
作者
CHEN, Yue

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given {32, 321, 3214, 0229, 87}, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (<=10000) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Do not output leading zeros.

Sample Input:
5 32 321 3214 0229 87
Sample Output:
22932132143287
很明顯這是一道排序題,這道題的學問主要在排序函數,不能使用通常的字符串比較函數,例如實例中,當32,321,3214這3個數同時存在於序列中時,如何決定這三個數的順序,可以肯定的是,當多個數有相同的前綴時,這幾個數出現時一定是相鄰的,如結果中的321 32 3214,方法就是當比較兩個字符串大小時如32和321,如果有相同前綴,則刪除較長的字符串中的前綴,並比較剩下的數的大小,即32和321的比較結果應該是32和1的比較結果,同理,321和3214的比較結果應該是321和4的比較結果,3214和32的比較結果應該等於14和32的比較結果,代碼如下:
本題目的另外一個坑點就是當所有的數都是0的時候,去除前導的0可能會使得整個數都被剪裁沒了,此時要進行特判,否則可能會發生“異常退出”的情況
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>

using namespace std;

vector<string> num;

bool cmp(string a, string b){
	int len[2];
	len[0] = a.length(), len[1] = b.length();
	int i = 0;
	while (i < len[0] && i < len[1]){
		if (a[i] < b[i])
			return true;
		else if (a[i] > b[i])
			return false;
		else;
		i++;
	}
	if (i < len[0])
		return cmp(a.substr(i),b);
	else if (i < len[1])
		return cmp(a,b.substr(i));
	else
		return true;//兩個數完全相同
}

int main(){
	string temp, ans;
	int n,k;
	cin >> n;
	vector<string>::iterator it;
	while (n--){
		cin >> temp;
		num.push_back(temp);
	}
	sort(num.begin(), num.end(), cmp);
	it = num.begin();
	while (it != num.end()){
		ans += *it;
		it++;
	}
	if ((k = ans.find_first_not_of('0')) != string::npos)//如果整個數都是0
		ans = ans.substr(k);
	else
		ans = "0";
	cout << ans << endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章