1 条题解

  • -1
    @ 2022-9-29 10:05:27

    分离两种类型

    #include <bits/stdc++.h>
    using namespace std;
    vector<int> a;
    vector<int> b;
    bool cmp(int x, int y)
    {
        return x > y;
    }
    int main()
    {
        for (int i = 1; i <= 10; i++)
        {
            int x;
            cin >> x;
            if (x % 2 == 1)
                a.push_back(x);
            else
                b.push_back(x);
        }
        sort(a.begin(), a.end(), cmp);
        sort(b.begin(), b.end());
        for (int i = 0; i < a.size(); i++)
            cout << a[i] << " ";
        for (int i = 0; i < b.size(); i++)
            cout << b[i] << " ";
        return 0;
    }
    

    相对累赘的比较函数

    #include <bits/stdc++.h>
    using namespace std;
    int a[15];
    bool cmp(int x, int y)
    {
        if (x % 2 == 1 && y % 2 == 0)
            return true;
        if (x % 2 == 0 && y % 2 == 1)
            return false;
        if (x % 2 == 1 && y % 2 == 1)
            return x > y;
        return x < y;
    }
    int main()
    {
        for (int i = 1; i <= 10; i++)
            cin >> a[i];
        sort(a + 1, a + 10 + 1, cmp);
        for (int i = 1; i <= 10; i++)
            cout << a[i] << " ";
        return 0;
    }
    
    

    更优雅的写法

    #include <bits/stdc++.h>
    using namespace std;
    int a[15];
    //自定义排序规则
    bool cmp(int x, int y)
    {
        //奇偶性不同时,偏序关系为前奇后偶
        if (x % 2 != y % 2)
            return x % 2 == 1 && y % 2 == 0;
        //都是奇数时从大到小
        if (x % 2 == 1)
            return x > y;
        //都是偶数时从小到大
        return x < y;    
    }
    int main()
    {
        for (int i = 1; i <= 10; i++)
            cin >> a[i];
        sort(a + 1, a + 10 + 1, cmp);
        for (int i = 1; i <= 10; i++)
            cout << a[i] << " ";
        return 0;
    }
    
    • 1

    信息

    ID
    401
    时间
    1000ms
    内存
    128MiB
    难度
    1
    标签
    (无)
    递交数
    78
    已通过
    54
    上传者