PAT (Basic Level) Practice 1023

1023. 组个最小数 (20)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CAO, Peng

给定数字0-9各若干个。你可以以任意顺序排列这些数字,但必须全部使用。目标是使得最后得到的数尽可能小(注意0不能做首位)。例如:给定两个0,两个1,三个5,一个8,我们得到的最小的数就是10015558。

现给定数字,请编写程序输出能够组成的最小的数。

输入格式:

每个输入包含1个测试用例。每个测试用例在一行中给出10个非负整数,顺序表示我们拥有数字0、数字1、……数字9的个数。整数间用一个空格分隔。10个数字的总个数不超过50,且至少拥有1个非0的数字。

输出格式:

在一行中输出能够组成的最小的数。

输入样例:
2 2 0 0 0 3 0 0 1 0
输出样例:
10015558

分析:思路不是很难,先输出一个非零的最小数,然后从零开始输出其余数字。不过需要考虑一下输入全零或输入仅有一位等几种特殊情况。在这里在输入时记录了数字的总个数,方便下面分情况讨论。

代码:

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int num[10] = {0};
	int cnt = 0;
	int temp;
	for(int i = 0; i <= 9; i++){
		cin >> temp;
		num[i] = temp;
		cnt += temp;
	}
	for(int i = 1; i <= 9; i++){
		if(num[i] != 0 && cnt == 1){
			cout << i << endl;
			num[i]--;
			cnt--;
			break;
		}else if(num[i] != 0 && cnt > 1){
			cout << i;
			num[i]--;
			cnt--;
			break;
		}
	}
	if(cnt != 0){
		for(int i = 0; i <= 9; i++){
			if(num[i] != 0){
				while(num[i] != 0){
					if(cnt != 0){
						cout << i;
						num[i]--;
						cnt--;
					}else if(cnt == 0){
						cout << i << endl;
						break;
					}	
				}
			}
		}
	}else{
		cout << 0 << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/g28_gwf/article/details/80171904
今日推荐