题目:https://www.luogu.org/problem/P1012
设有n个正整数(n≤20)(n≤20),将它们联接成一排,组成一个最大的多位整数。
例如:n=3n=3时,33个整数1313,312312,343343联接成的最大整数为:3433121334331213
又如:n=4n=4时,44个整数77,1313,44,246246联接成的最大整数为:74246137424613
code1:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(string a, string b)
{
return a+b > b+a;
}
int main()
{
int n;
cin >> n;
string a[20];
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a,a+n,cmp);
for(int i = 0; i < n; i++)
{
cout << a[i];
}
return 0;
}
code2:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 30;
int n;
struct node
{
string str;
bool operator > (const node &o) const
{
if(str + o.str > o.str + str)
return true;
return false;
}
}str[MAXN];
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> str[i].str;
}
sort(str, str + n, greater<node>());
for(int i = 0; i < n; i++)
cout << str[i].str;
cout << endl;
return 0;
}
关于code2中的重载:
bool operator > (const node &o) const { }
写成 bool operator > (node o) const { } 是不会报错的, node o 和 node &o 的区别是会不会开辟新的变量, node o 慢一些, node &o很快,但是很不安全,操作错误可能把o的值给改变了。第二个const是为了防止把结构体里的值给改变了,这个函数的目的是为了获取一个值,正常是不会改变这个结构体里的值,如果改变了,不加const的情况下,并不会报错,加上就报错了。
所以,第一个const防止o的值被改变,第二个const防止结构体里的值被改变。在写代码过程中尽量多使用const,这是一个很好的习惯。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100;
int n;
struct node
{
int num;
/*
从大到小排序
bool operator > (const node &o) const
{
return num > o.num;
}
*/
/*
从小到大排序
*/
bool operator < (const node &o) const
{
return num < o.num;
}
}a[MAXN];
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i].num;
/*
从大到小输出
sort(a + 1, a + 1 + n, greater<node>());
for(int i = 1; i <= n; i++)
cout << a[i].num << " ";
cout << endl;
*/
/*
从小到大输出
*/
sort(a + 1, a + 1 + n, less<node>());
for(int i = 1; i <= n; i++)
cout << a[i].num << " ";
cout << endl;
return 0;
}