C++题目描述可多宇宙中对于一个整数有特殊的排序方法它们会把这个整数的每一位相加相加的和越大排名越靠前。如果有两个整数各位相加之和一样那么原数字较小的排在前面。输入描述第一行是一个整数 n 0 n 100表示有多少个数;第二行有 n 个整数每个数在 0 到 10000 之间用空格隔开n 个整数互不相同。输出描述输出为 n 行按题目要求的规则对整数进行排序每行一个整数样例1输入40 1001 1
一种解法是使用vector和sort函数来对整数进行排序。首先将输入的整数存放在vector中,然后定义一个自定义的比较函数,该函数按照题目要求的规则对整数进行比较。最后使用sort函数对vector进行排序,输出排序后的结果。
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 自定义的比较函数
bool compare(int a, int b) {
int sum_a = 0, sum_b = 0;
// 计算整数a的每一位之和
while (a) {
sum_a += a % 10;
a /= 10;
}
// 计算整数b的每一位之和
while (b) {
sum_b += b % 10;
b /= 10;
}
// 如果两个整数的每一位之和不同,按照之和从大到小排序
if (sum_a != sum_b) {
return sum_a > sum_b;
}
// 如果两个整数的每一位之和相同,按照原数字从小到大排序
return a < b;
}
int main() {
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
// 使用自定义的比较函数对整数进行排序
sort(nums.begin(), nums.end(), compare);
// 输出排序后的结果
for (int i = 0; i < n; i++) {
cout << nums[i] << endl;
}
return 0;
}
该解法的时间复杂度为O(nlogn),其中n为整数的个数
原文地址: http://www.cveoy.top/t/topic/h0pV 著作权归作者所有。请勿转载和采集!