排序刷题11

题目来源:[NOIP1998 提高组] 拼数 - 洛谷

解题思路:这道题重点在于怎么把数字拼接,得到最大的值。这里可以用to_string()函数,将数字先转换为字符再拼接,最后得到拼接的最大值。ps:需要考虑两个相邻字符的前后两种拼接方式,ab,ba。

#include
#include
#include
#include


using namespace std;

bool cmp(const int& a, const int& b)
{
	// 将数字转换为字符串,以便进行拼接
	string ab = to_string(a) + to_string(b);
	string ba = to_string(b) + to_string(a);
	// 比较拼接后的字符串
	return ab > ba;

}


int main()
{
	int n;
	cin >> n;
	vectora(n);
	//读取每个数字
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	// 使用自定义的比较函数进行排序
	sort(a.begin(), a.end(), cmp);
	// 输出结果
	for (int b : a)
	{
		cout << b;
	}
	cout << endl;
	return 0;
}

你可能感兴趣的:(排序,算法,数据结构,c++,排序算法,c语言)