【贪心】最大整数/数串
题目描述
设有n个正整数,将他们连接成一排,组成一个最大的多位整数。
如:n=3时,3个整数13,312,343,连成的最大整数为34331213。
如:n=4时,4个整数7,13,4,246连接成的最大整数为7424613。
输入描述:
有多组测试样例,每组测试样例包含两行,第一行为一个整数N(N<=100),第二行包含N个数(每个数不超过1000,空格分开)。
输出描述:
每组数据输出一个表示最大的整数。
#include <iostream>
#include <string>
using namespace std;
int n;
string a[101];
string output;
int x;
void greedy();
int main()
{
while(cin>>n)
{
for(int i=0; i<n; i++)
{
cin>>x;
a[i]=to_string(x);
}
greedy();
cout<<output<<endl;
}
return 0;
}
void greedy()
{
for(int i=0; i<n; i++)
{
for(int j=i; j<n; j++)
{
if(a[i]+a[j]<a[j]+a[i])
{
swap(a[i],a[j]);
}
}
}
output=a[0];
for(int i=1; i<n; i++)
{
output+=a[i];
}
}
【2018/11/8后记】
1、如果codeblocks里报错“ 'to_string' was not declared in this scope”,那么需要打开Settings-Complier,在这一项后面打勾