CPP贪心算法示例

设有n个正整数(n ≤ 20),将它们联接成一排,组成一个最大的多位整数。

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

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

cpp 复制代码
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string intToStr(int x)
{
    return to_string(x);//例如 12345 会变成 "12345"
}

// 比较函数,用于确定两个数字拼接后的顺序
bool compare(const int& x, const int& y) {
    string xStr = intToStr(x);
    string yStr = intToStr(y);
    string xyStr = xStr + yStr;// + 运算符可以直接链接两个string类型函数
    string yxStr = yStr + xStr;
    return xyStr > yxStr; // 返回拼接后较大的那个顺序
}

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    // 使用自定义的比较函数对向量进行排序
    sort(a.begin(), a.end(), compare);//注意这里只能用迭代器不能用sort(arr, arr + n, compare)
    // 输出排序后的结果
    for (size_t i = 0; i < a.size(); ++i) {
        cout << a[i];
    }
    cout << endl;
    return 0;
}
相关推荐
LYFlied8 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠9 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr87310 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu11 小时前
整数数组匹配
数据结构·c++·算法
smj2302_7968265211 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied12 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-13 小时前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄13 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳13 小时前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang13 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽