#136Medium
Sorting by remainder
Time: 1 s · Memory: 256 MB
- Sorting
Statement
You are given integers and a number . Sort the numbers by these rules:
- First by increasing remainder . The remainder keeps the sign of the number (like
%in C++): for example, , . - If the remainders are equal, an odd number comes before an even one.
- If both are odd, the larger comes first; if both are even, the smaller comes first.
Input format
The first line contains and (, ). The second line contains integers ().
Output format
A single line with numbers — the sorted array.
Examples
Input
10 3 1 2 3 4 5 6 7 8 9 10
Output
9 3 6 7 1 4 10 5 2 8
Input
7 3 -7 7 -4 4 0 -3 3
Output
-7 -4 3 -3 0 7 4
Note
The three rules form one comparator: different remainders — by remainder; different parity — odd first; otherwise odd numbers in decreasing and even numbers in increasing order. A negative number can be odd too: is odd.
In Python -7 % 3 gives 2, which is not the remainder from the statement. Get the signed remainder with math.fmod or -(abs(a) % M). In the second example the remainders are: , , , , , , ; the answer is -7 -4 3 -3 0 7 4.
Source: UVa 11321.
