您的位置:首页 > 其它

贪心算法——最大整数问题详解

2016-04-06 14:52 267 查看
贪心算法——最大整数问题详解:

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

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

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

输入:n

N个数

输出:连成的多位数

算法分析:此题很容易想到使用贪心法,在考试时有很多同学把整数按从大到小的顺序连接起来,测试题目的例子也都符合,但最后测试的结果却不全对。按这种标准,我们很容易找到反例:12,121应该组成12121而非12112,那么是不是相互包含的时候就从小到大呢?也不一定,如12,123就是12312而非12123,这种情况就有很多种了。是不是此题不能用贪心法呢?

其实此题可以用贪心法来求解,只是刚才的标准不对,正确的标准是:先把整数转换成字符串,然后在比较a+b和b+a,如果a+b>=b+a,就把a排在b的前面,反之则把a排在b的后面。
c++源代码:
#if 1

//贪心算法——最大整数

#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;

}

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: