二、算法题(35分)
题目描述:
设有n个正整数,将它们联接成一排,组成一个最小的多位整数。
程序输入:n个数
程序输出:联接成的多位数
例如:
n=2时,2个整数32,321连接成的最小整数为:32132,
n=4时,4个整数55,31,312, 33 联接成的最小整数为:312313355
[题目要求]
1. 给出伪代码即可,请给出对应的文字说明,并使用上面给出的例子试验你的算法。
2. 给出算法的时间空间复杂度。
3. 证明你的算法。(非常重要)
直接贴程序吧:
#include
<
functional
>
#include < iostream >
#include < string >
#include < sstream >
#include < algorithm >
#include < math.h >
using namespace std;
class Less: public binary_function < int , int , bool > {
public :
bool operator ()( int a, int b){
stringstream ss;
string str_a,str_b;
ss << a << " " << b;
ss >> str_a >> str_b;
return (a * powf( 10 ,str_b.length()) + b) < (b * powf( 10 ,str_a.length()) + a);
}
};
int main(){
int a[] = { 1562 , 15 , 68 , 622 };
sort(a,a + sizeof (a) / sizeof ( int ),Less());
ostream_iterator < int > os(cout, " " );
copy(a,a + sizeof (a) / sizeof ( int ),os);
}
#include < iostream >
#include < string >
#include < sstream >
#include < algorithm >
#include < math.h >
using namespace std;
class Less: public binary_function < int , int , bool > {
public :
bool operator ()( int a, int b){
stringstream ss;
string str_a,str_b;
ss << a << " " << b;
ss >> str_a >> str_b;
return (a * powf( 10 ,str_b.length()) + b) < (b * powf( 10 ,str_a.length()) + a);
}
};
int main(){
int a[] = { 1562 , 15 , 68 , 622 };
sort(a,a + sizeof (a) / sizeof ( int ),Less());
ostream_iterator < int > os(cout, " " );
copy(a,a + sizeof (a) / sizeof ( int ),os);
}