1038 Recover the Smallest Number

本文详细介绍了如何从一组数字段中找到最小组合的方法,并分析了常见的优化策略。通过对比不同实现方式,揭示了效率提升的关键点。此外,文章还讨论了在处理以0开头的数字时的常见陷阱及解决方案。

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
解题思路:就是尽量将小的数字开始的数放在前面,让小的数字占据高位,最后形成的数也就越小。
注意点:一开始写程序的时候,我在输入的时候就将以0为开头的数字直接将0去掉之后存放在向量中,因为我认为是每个数字实际的值在进行组合,但是后来提交一直错误,尝试改了一下,发现是这个问题,这个题对于 2 01 02 的输入正确输出应该是102而不是我之前想的12.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(const string ss1, const string ss2){
	int index = 0;
	string s1 = ss1,s2 = ss2;
	if (s1.length() < s2.length()){
		while (s1.length() < s2.length()){
			s1 = s1 + ss1;
		}
	}
	else if (s1.length() > s2.length()){
		while (s2.length() < s1.length()){
			s2 = s2 + ss2;
		}
	}
	while (index < s1.length() && index < s2.length()){
		if (s1[index] < s2[index]){
			return true;
		}
		else if (s1[index] > s2[index]){
			return false;
		}
		else{
			index++;
		}
	}
	return true;
}
int main(){
	for (int n; cin >> n;){
		vector<string>vec;
		while (n--){
			string s;
			cin >> s;
			vec.push_back(s);
		}
		sort(vec.begin(), vec.end(), cmp);
		string res = "";
		res += vec[0];
		for (int i = 1; i < vec.size(); i++){
			res += vec[i];
		}
		if (res.find_first_not_of('0') != -1){
			cout << res.substr(res.find_first_not_of('0'))<<endl;
		}
		else{
			cout << "0" << endl;
		}
	}
	return 0;
}
后来我看到别人写的一个比较函数,比我的简单多了,我要进行那么多的判断,别人两行就解决了。
bool cmp(const string s1, const string s2){
	return s1 + s2 < s2 + s1;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值