a703中等帶負數餘數的多層排序鍵
CPE:Sort! Sort!! And Sort!!! (UVa 11321)
精確轉譯四層排序規則並保持C語言餘數定義。
解題思路
排序鍵第一層是x對M的C式餘數;第二層讓奇數在前;第三層在奇數群用−x作遞增鍵,等價數值遞減,在偶數群用x作遞增鍵。這些鍵按字典序比較即可完全表達題意,也保證比較器一致。
C++的整數%已符合商向0截斷;Python負數%會取非負餘數,所以改成x%M(x≥0)或−((-x)%M)(x<0)。判奇偶可檢查x%2!=0,負奇數同樣成立。C++先存long long避免對最小32位元整數取負溢位。每組先印原N M,遇到0 0也要輸出該終止行後才停止。
Step-by-step animation
示意:M=3,數字 −4,−1,2,5
步驟 1 / 3
餘數
−4、−1的C式餘數為−1,2、5為2。
-4:-1
-1:-1
2:2
5:2
- 餘數群
- -1,2
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
int main() {
int n, m;
while (cin >> n >> m) {
cout << n << ' ' << m << '\n';
if (!n && !m)
break;
vector<long long> a(n);
for (auto &x : a)
cin >> x;
auto key = [&](long long x) {
bool odd = x % 2 != 0;
return make_tuple(x % m, odd ? 0 : 1, odd ? -x : x);
};
sort(a.begin(), a.end(), [&](long long x, long long y) { return key(x) < key(y); });
for (auto x : a)
cout << x << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。