#C3383. Sorting Books by Binary Ones

    ID: 46804 Type: Default 1000ms 256MiB

Sorting Books by Binary Ones

Sorting Books by Binary Ones

You are given a list of book IDs, and your task is to sort them according to the following rules:

  • First, by the number of 1's in their binary representation (in ascending order). Formally, define \( f(x) \) as the number of ones in the binary representation of \( x \). Thus, if \( f(a) < f(b) \), then \( a \) should come before \( b \).
  • If two numbers have the same number of 1's, they should be ordered by their numerical value in ascending order.

For example, for the book IDs [3, 7, 8, 6, 5]:

3 in binary = 11    (2 ones)
7 in binary = 111   (3 ones)
8 in binary = 1000  (1 one)
6 in binary = 110   (2 ones)
5 in binary = 101   (2 ones)

The sorted order would be: 8 (1 one), 3 (2 ones), 5 (2 ones), 6 (2 ones), 7 (3 ones) yielding the array [8, 3, 5, 6, 7].

inputFormat

The input is read from standard input (stdin) and contains two lines:

  1. The first line contains an integer \( n \) denoting the number of book IDs.
  2. The second line contains \( n \) space-separated integers representing the book IDs.

outputFormat

Output the sorted list of book IDs in a single line, where the numbers are separated by a single space. The output is written to standard output (stdout).

## sample
5
3 7 8 6 5
8 3 5 6 7