PAT--1038 Recover the Smallest Number

題目鏈接:https://pintia.cn/problem-sets/994805342720868352/problems/994805449625288704

題目大意:給出n個數字的片段,會有前導零,讓你求出組合後的最小的數,最終結果不能有前導零。

分析:其實很自然的能想到排序,但是怎麼排序呢?假設我們把這些數排列起來,有兩個相鄰的片段a,b,如果我們把a和b交換位置後數會變小,那必然要交換a和b,所以依據這個原理排序就可以了。

#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 5;
int n;
string s[N];
bool cmp(const string a, const string b) {
	return (a + b) < (b + a);
}
int main() {
	cin >> n;
	for(int i = 1; i <= n; i++)
		cin >> s[i];
	sort(s + 1, s + n + 1, cmp);
	int flag = 0;
	for(int i = 1; i <= n; i++) {
		for(int j = 0; j < s[i].length(); j++) {
			if(flag == 0 && s[i][j] == '0') continue;
			flag = 1;
			cout << s[i][j];
		}
	}
	if(!flag) cout << "0";
	cout << endl;
	return 0;
}

 

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