1407B.md (2681B)
1 Source: https://codeforces.com/problemset/problem/1407/B 2 3 B. Big Vova 4 5 time limit per test 6 7 1 second 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years. 22 23 You're given $n$ positive integers $a_1, a_2, \dots, a_n$. Using each of them exactly at once, you're to make such sequence $b_1, b_2, \dots, b_n$ that sequence $c_1, c_2, \dots, c_n$ is lexicographically maximal, where $c_i=GCD(b_1,\dots,b_i)$ - the greatest common divisor of the first $i$ elements of $b$. 24 25 Alexander is really afraid of the conditions of this simple task, so he asks you to solve it. 26 27 A sequence $a$ is lexicographically smaller than a sequence $b$ if and only if one of the following holds: 28 29 * $a$ is a prefix of $b$, but $a \ne b$; 30 * in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$. 31 32 Input 33 34 Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). Description of the test cases follows. 35 36 The first line of each test case contains a single integer $n$ ($1 \le n \le 10^3$) — the length of the sequence $a$. 37 38 The second line of each test case contains $n$ integers $a_1,\dots,a_n$ ($1 \le a_i \le 10^3$) — the sequence $a$. 39 40 It is guaranteed that the sum of $n$ over all test cases does not exceed $10^3$. 41 42 Output 43 44 For each test case output the answer in a single line — the desired sequence $b$. If there are multiple answers, print any. 45 46 Example 47 48 Input 49 50 ``` 51 7 52 2 53 2 5 54 4 55 1 8 2 3 56 3 57 3 8 9 58 5 59 64 25 75 100 50 60 1 61 42 62 6 63 96 128 88 80 52 7 64 5 65 2 4 8 16 17 66 ``` 67 68 Output 69 70 ``` 71 5 2 72 8 2 1 3 73 9 3 8 74 100 50 25 75 64 75 42 76 128 96 80 88 52 7 77 17 2 4 8 16 78 ``` 79 80 Note 81 82 In the first test case of the example, there are only two possible permutations $b$ — $[2, 5]$ and $[5, 2]$: for the first one $c=[2, 1]$, for the second one $c=[5, 1]$. 83 84 In the third test case of the example, number $9$ should be the first in $b$, and $GCD(9, 3)=3$, $GCD(9, 8)=1$, so the second number of $b$ should be $3$. 85 86 In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation $b$.