题的链接:P1012 拼数
注意点:
直接从大到小排是不对的:如(321 32 出现 32132 > 32321的情况);
参考代码1.0: 就是字符串的排序,大的在前,输出即可,但是不能直接排,以防出现(321 32 出现 32132 > 32321的情况),可以用a + b > b + a来保证关系的正确性!!!
#include <string>
#include <iostream>
#include <algorithm>
using namespace std
;
string str
[100];
int n
;
bool cmp(string a
, string b
)
{
return (a
+ b
) > (b
+ a
);
}
int main()
{
cin
>> n
;
for(int i
= 0; i
< n
; i
++) cin
>> str
[i
];
sort(str
, str
+ n
, cmp
);
for(int i
= 0; i
< n
; i
++) cout
<< str
[i
];
return 0;
}
参考代码2.0: 使用冒泡排序!!!
#include <string>
#include <iostream>
#include <algorithm>
using namespace std
;
string str
[100];
int n
, s
[10];
int main()
{
cin
>> n
;
for(int i
= 0; i
< n
; i
++) cin
>> str
[i
];
for(int i
= 0; i
< n
- 1; i
++)
for(int j
= i
+ 1; j
< n
; j
++)
if(str
[i
] + str
[j
] < str
[j
] + str
[i
])
swap(str
[i
], str
[j
]);
for(int i
= 0; i
< n
; i
++) cout
<< str
[i
];
return 0;
}
转载请注明原文地址: https://mac.8miu.com/read-498421.html