開啟章節選單

11321 Sort! Sort!! and Sort!!!

解題思路

我們開一個 vector 陣列來儲存所有數字,並撰寫一個自訂的 cmp 比較函數。根據題目的敘述撰寫判斷式,若須交換則回傳 1

程式碼

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int n, m;

bool cmp(int x, int y) {
    // 若奇偶數不同,則奇數排前面
    if ((x % m) != (y % m)) return (x % m) < (y % m);

    // 兩奇數除餘數相等,較大的奇數排前面
    if ((x % 2) * (y % 2)) return x > y;

    // 兩偶數除餘數相等,較小的偶數排前面
    if ((x % 2 == 0) && (y % 2 == 0)) return x < y;

    // 奇偶相異且兩餘數相等,則奇數要排偶數前面
    return (x % 2);
}

int main() {
    while (cin >> n >> m){
        if (n == 0 && m == 0) break;
        cout << n << " " << m << "\n";

        vector<int> v(n);
        for (int i = 0; i < n; i++) cin >> v[i];

        sort(v.begin(), v.end(), cmp);

        for (int i = 0; i < n; i++) cout << v[i] << '\n';
    }
    cout << "0 0\n";
}