問題一覧 > 通常問題

No.14 LCM Sort

レベル : / 実行時間制限 : 1ケース 5.000秒 / メモリ制限 : 512 MB / 標準ジャッジ問題
タグ : (AC するまで非表示) / 解いたユーザー数 160
作問者 : yuki2006
お気に入りにしたユーザー ProblemId : 38 / 自分の提出
問題文最終更新日: 2024-05-04 02:58:35
This statement was translated by AI (claude-opus-5-5, effort medium) and may contain errors or differ in nuance from the original. The original statement takes precedence. Back to the original
yukicoder contest 14 (順位表) の他の問題:

Problem Statement

Larry, who has just learned about the least common multiple, came up with something called "LCM sort".

Here, "LCM sort" is defined as follows:
\(N\) integers (possibly with duplicates) are given, denoted by \(a_i\ (1 \leq i \leq N)\).
Fix \(a_1\), take the least common multiple of each of \(a_2〜a_N\) with \(a_1\), and rearrange them in ascending order of the least common multiple.
(If there are multiple elements with the smallest least common multiple, the one with the smaller value as $a_i$ takes priority.)

Larry
renames the resulting array as \(a_1 \dots a_N\) and continues the operation.
Next, he fixes \(a_2\) (keeping \(a_1\) fixed as well) and performs "LCM sort" on \(a_3〜a_N\).
Next, he fixes \(a_3\), and so on. Find the sequence obtained when this has been continued up to \(a_N\).

(In C/C++ a naive solution barely passes, but there is a way to reduce the computational complexity, so this problem is rated ★4.)

Input

\(N\)
\(a_1\ a_2\ \dots\ a_i\ \dots\ a_N\)

The \(1\)st line contains \(N\ (1 \leq N \leq 10000)\), the number of integers.
The \(2\)nd line contains the value of each integer \(a_i\ (1 \leq i \leq N, 1 \leq a_i \leq 10000)\), separated by single-byte spaces.

Output

Output the sequence obtained after continuing from \(a_1\) to \(a_N\), separated by single-byte spaces.
Print a newline at the end.

Sample

Sample 1
Input
5
1 2 3 4 5
Output
1 2 4 3 5

First, fix the \(1\)st element, \(1\), and perform LCM sort on the elements after it, which gives
1 2 3 4 5
Next, fix the \(2\)nd element, \(2\), and perform LCM sort on the elements after it, which gives
1 2 4 3 5
Next, fix the \(3\)rd element, \(4\), and continuing in this way leads to the answer.

Sample 2
Input
5
4 8 1 2 4
Output
4 1 2 4 8

The same number may appear more than once. If the least common multiples are equal during sorting, the smaller original number takes priority.

Sample 3
Input
10
9 9 3 7 5 9 1 5 2 1
Output
9 1 1 2 3 9 9 5 5 7

提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。