Official algorithmic problem description and constraints.
Yousef has given you an array π
of π
positive integers.
Let π(π)
denote the number of subarrays
β
of π
whose product is divisible by 6
.
More formally, for every pair of indices π
and π
such that 1β€πβ€πβ€π
, consider the subarray π
π
,π
π+1
,β¦,π
π
. This subarray is counted if the product of its elements is divisible by 6
.
For example, if π=[1,6,2]
, then the subarrays whose products are divisible by 6
are [6]
, [1,6]
, [6,2]
, and [1,6,2]
, so π(π)=4
.
Your task is to reorder the elements of the array π
so that π(π)
is minimized. If there are multiple ways to do this, you may output any of them.
β
An array π
is a subarray of an array π
if π
can be obtained from π
by deleting several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.
Input
The first line of the input contains an integer π‘
(1β€π‘β€10
4
) β the number of test cases.
The first line of each test case contains an integer π
(1β€πβ€2β 10
5
) β the size of the array.
The second line of each test case contains π
integers π
1
,π
2
,β¦,π
π
(1β€π
π
β€10
9
) β the elements of the array.
It is guaranteed that the sum of π
over all test cases does not exceed 2β 10
5
.
Output
For each test case, output the array after reordering it in such a way that π(π)
is minimized. If there are multiple answers, you may output any of them.
Example
Input
Copy
5 6 12 7 9 4 18 5 4 3 6 2 8 7 1 10 15 20 3 6 9 5 11 14 21 2 5 3 6 6 6
Output
Copy
12 18 4 7 5 9 2 8 3 6 6 10 20 1 15 3 9 21 5 11 2 14 6 6 6
Note
In the first test case, an optimal arrangement is π=[12,18,4,7,5,9]
. The subarrays whose products are divisible by 6
are:
Therefore, π(π)=12
. It can be proven that no other arrangement yields a smaller value of π(π)
.
Detailed video explanations, mathematical intuition, and clean C++ implementation code.