使用C++ map 或者 sort 把几个正整数组合成最小整数或最大整数

版权声明:个人整理,仅供参考,请勿转载,如有侵权,请联系[email protected] https://blog.csdn.net/mooe1011/article/details/88836434

连续输入正整数,比如12 34 2 21,把他们整合成一个最小正整数,即1221234

注意到map是按字典排序,但有一种情况321,32,字典排序默认长的在后面,正确情况应该是组合成32132.我们可以考虑在读入的时候加入一个字母即可,输出记得去掉字母

#include<bits/stdc++.h>
using namespace std;


int main() {
	//freopen("input.txt", "r", stdin);
	string s;
	map<string, int> res;
	while (cin >> s) {
		res[s + "a"]++;
	}

	for (auto i = res.begin(); i != res.end(); i++) {		
		cout << i->first.substr(0, i->first.size() - 1);
	}
	cout << endl;
	return 0;
}

如果不用map可以考虑一下sort对string进行排序

int main() {
	//freopen("input.txt", "r", stdin);
	string s;
	vector<string> res;
	while (cin >> s) {
		res.push_back(s + "a");
	}	
	sort(res.begin(), res.end());
	for (string s : res) {
		cout << s.substr(0, s.size() - 1);
	}
	cout << endl;
	return 0;
}

求最大只需要加入greater<string>即可

int main() {
	//freopen("input.txt", "r", stdin);
	string s;
	map<string, int, greater<string> > res;
	while (cin >> s) {
		res[s]++;
	}

	for (auto i = res.begin(); i != res.end(); i++) {		
		cout << i->first;
	}
	cout << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mooe1011/article/details/88836434