码迷,mamicode.com
首页 > 编程语言 > 详细

【贪心算法】最大整数

时间:2017-06-10 21:25:30      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:main   end   nbsp   pad   贪心   names   one   list   cin   

题目:

设有n个正整数,将它们连接成一排,组成一个最大的多位整数。

例如:n=3时,3个整数13,312,343,连成的最大整数为34331213。

又如:n=4时,4个整数7,13,4,246,连成的最大整数为7424613。


输入:

n

输入n个数。

输出:

连成的多位数。

思路:

让这几个数排排序连接成最大的整数,所以应考虑,各个整数顺序,那么对这几个整数排序的准则是什么?

准则:设两个整数是a,b,如果a+b大于b+a,那么a在b的前面,反之,b在a前面也就是局部的解

全局的解就是所有整数的连接顺序,既然要用到连接所以用string。

 

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;
string str[3] = {""};

string GetStrFromInt(int n)
{
stringstream ss;
string s;
ss << n;
ss >> s;
return s;
}

string GreedyAlgorithm(int n)
{
int arr[4] = { 0 };
string strmax = "";
cout << "Please Input the Data:" << endl;
int m = n;
while (m--)
{
if (!(cin >> arr[m]))
{
cout << "输入数据不合法" << endl;
return NULL;
}
}


//核心算法———将整数转为字符串,连接起来进行比较
for (int i = 0; i < n; ++i)
{
str[i] = GetStrFromInt(arr[i]);
}


for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if ((str[i]+str[j]).compare(str[j] + str[i]) < 0)
{
string temp=str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
for (int i = 0; i < n; ++i)
{
strmax += str[i];
}
return strmax;
}


int main()
{
int n;
cout << "Please Input Datas:" << endl;
if (cin >> n)
cout << GreedyAlgorithm(n) << endl;
else
cout << "输入数据不合法" << endl;
return 0;
}

 

C++知识点总结:

①将整数转成字符串:需要头文件#include <sstream>具体代码如下:

string GetStrFromInt(int n)
{
stringstream ss;
string s;
ss << n;
ss >> s;
return s;
}

②字符串连接:string 类型的变量可以直接用“+”,“+=”连接。

③字符串比较

string 字符串可以直接用"<",">"直接比较。

int strcmp(const char firststring[], const char secondstring);(字符逐个比较

 

【贪心算法】最大整数

标签:main   end   nbsp   pad   贪心   names   one   list   cin   

原文地址:http://www.cnblogs.com/LuRenJiang/p/6978265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!