Someday, It Would Be Nice to Get Sorted
InterviewTime limit2sMemory limit1024 MB
Adjacent coprime elements may be swapped any number of times; output the lexicographically smallest sequence that can be reached.
- Level
Medium6 of 10
- Topics
- Topological sort, Greedy, Number theory
- Solved
- No attempts yet
Problem
There is a sequence of positive integers. You may perform the following operation as many times as you want. You may also perform no operation at all.
- When two adjacent elements of the sequence are coprime, swap the order of those two elements.
Two numbers are coprime when their greatest common divisor is . After the operations, find the sequence that is lexicographically smallest.
Input
The first line contains the length of the sequence .
The second line contains positive integers separated by spaces.
Output
Print the lexicographically smallest sequence after the operations on one line, with the elements separated by spaces.
Hint
A sequence is lexicographically smaller than another sequence when:
- The first element of the smaller sequence is smaller than the first element of the other sequence.
- If the first elements are equal, the sequences are compared again after removing the first element, and the one that is smaller in this comparison is lexicographically smaller.
An empty sequence is lexicographically smaller than any other sequence. The lexicographically smallest sequence is one that is less than or equal to every other sequence in lexicographic order.