4653. 数位排序

摘要
Title: 4653. 数位排序
Tag: 排序
Memory Limit: 64 MB
Time Limit: 1000 ms

Powered by:NEFU AB-IN

Link

4653. 数位排序

  • 题意

    小蓝对一个数的数位之和很感兴趣,今天他要按照数位之和给数排序。
    当两个数各个数位之和不同时,将数位和较小的排在前面,当数位之和相等时,将数值小的排在前面。
    例如,2022 排在 409 前面,因为 2022 的数位之和是 6,小于 409 的数位之和 13。
    又如,6 排在 2022 前面,因为它们的数位之和相同,而 6 小于 2022。
    给定正整数 n,m,请问对 1 到 n 采用这种方法排序时,排在第 m 个的元素是多少?

  • 思路

    结构体排序

  • 代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    /*
    * @Author: NEFU AB-IN
    * @Date: 2023-01-04 09:14:03
    * @FilePath: \Acwing\4653\4653.cpp
    * @LastEditTime: 2023-01-04 09:26:51
    */
    #include <bits/stdc++.h>
    using namespace std;
    #define N n + 100
    #define int long long
    #define SZ(X) ((int)(X).size())
    #define IOS \
    ios::sync_with_stdio(false); \
    cin.tie(nullptr); \
    cout.tie(nullptr)
    #define DEBUG(X) cout << #X << ": " << X << '\n'
    typedef pair<int, int> PII;

    #undef N
    const int N = 1e6 + 10;

    // #undef int

    struct sa
    {
    int n, sum;
    } a[N];

    signed main()
    {
    IOS;

    int n, m;
    cin >> n >> m;
    auto f = [&](int x) {
    int res = 0;
    while (x)
    {
    res += x % 10;
    x /= 10;
    }
    return res;
    };
    for (int i = 1; i <= n; ++i)
    {
    a[i].n = i;
    a[i].sum = f(i);
    }

    auto cmp = [&](const sa a, const sa b) {
    if (a.sum != b.sum)
    return a.sum < b.sum;
    else
    return a.n < b.n;
    };

    sort(a + 1, a + 1 + n, cmp);

    cout << a[m].n;

    return 0;
    }
使用搜索:谷歌必应百度