We need to reorder a given list of numbers (all distinct? not necessarily? Usually such problems guarantee distinct? Let's see examples: [4,8,6,3,12,9] all distinct. [42,28,84,126] distinct. [1000000000000000000, 3000000000000000000] distinct. Possibly they could be duplicates? If duplicates exist, then multiple possible sequences? Problem says "the answer exists", we need to output any valid order. Usually numbers are distinct because operations are one-to-one: dividing by 3 and multiplying by 2 yield distinct numbers? Could produce duplicate if a number appears multiple times? Possibly not but we don't need to handle duplicates because constraints guarantee existence and likely numbers are distinct? However not explicitly stated. But typical problem: CF 977B? Actually it's from Codeforces: "Polycarp and the Day of Pi"? No. It's "Polycarp and the Game of Numbers"? Actually there is Codeforces problem "Polycarp and the Day of Pi"? That's about digits. There is problem "Polycarp and the Game of Numbers" maybe? Actually I recall problem: "Polycarp and the Game of Numbers" but not sure. There's "Polycarp and Div 3"? Not.
Anyway, we need to find a permutation of the given numbers such that each adjacent pair satisfies: next = previous / 3 (if divisible) OR next = previous * 2.
We can think of the sequence as a chain (list) where each step either multiplies by 2 or divides by 3. Since we start from some initial x and perform n-1 operations. The resulting sequence in order is a path where each move is either *2 or /3.
We need to find an ordering of the given multiset that is a valid such path. It is guaranteed that one exists.
Observation: The operations are not symmetric; they are directed. The order of writing down numbers is such that from one number to next, we apply either /3 or 2. So it's like we have a directed graph on the numbers: from a we have edges to a2 (if that number is present) and to a/3 (if a divisible by 3 and a/3 present). We need to find a Hamiltonian path that uses all vertices exactly once, respecting that the edges are only in these directions. But we don't need to match the start? Actually we need to output a sequence that matches the order: each next is either previous * 2 or previous / 3. This means the direction from previous to next is either multiplying by 2 or dividing by 3. So if we have an edge from u to v meaning v = u*2 or v = u/3, then the path follows these edges. So it's a directed Hamiltonian path. The path is simple.
But we can also think in terms of ordering by "dependency" because each number appears exactly once in the operations. Let's consider the transformation: starting from some x, each operation either multiplies by 2 or divides by 3. So the sequence is determined by a starting number and a sequence of operations. Over the whole sequence, the exponent of 2 and 3 in the prime factorization of the numbers change. Let each number be represented as 2^a * 3^b * c, where c is not divisible by 2 or 3. Since operations are *2 (increase a by 1) or /3 (decrease b by 1). So if we think about the process, the product of the numbers? Not directly.
But note that the only allowed operations involve factors of 2 and 3; other prime factors remain unchanged throughout. Since we start with some integer x, which may have other prime factors. Then multiplying by 2 adds factor 2; dividing by 3 removes factor 3 (if divisible). So the numbers in the sequence all share the same "core" part c (the part not divisible by 2 or 3), because multiplying/dividing by 2 or 3 does not affect other primes. However, dividing by 3 requires divisibility by 3, so that ensures that the core part remains the same? Actually if x is divisible by 3, dividing by 3 reduces exponent of 3, but core part (the part not divisible by 2 or 3) stays same because 3 doesn't affect other primes. Multiplying by 2 adds factor 2; core part unchanged. So indeed all numbers in the sequence must have the same "c" (the part not divisible by 2 or 3) because starting from initial x with core c, all operations preserve c. So all numbers in the given list must share the same core (the odd part after removing all factors of 2 and 3). That is a necessary condition. The problem guarantees existence, but it's a good property.
Thus we can factor each number as c * 2^a * 3^b, where c is not divisible by 2 or 3. Since c is common across all numbers, we can ignore it for ordering; the relative ordering depends on exponents (a, b). Let’s denote exponent of 2 as a_i, exponent of 3 as b_i.
Now the operations:
- If we go from x to x*2: then (a, b) -> (a+1, b)
- If we go from x to x/3: then (a, b) -> (a, b-1) (requires b >=1)
Thus the sequence of exponent pairs changes as: each step either increases a by 1 or decreases b by 1.
This is reminiscent of a path on a grid from some start (a0,b0) to some end after n-1 steps. The moves are either (1,0) or (0,-1). So the sum a + b changes: (a+b) either increases by 1 or decreases by 1? Actually (1,0) increases sum by 1; (0,-1) decreases sum by 1. So sum a+b changes by ±1.
Therefore the sequence of (a,b) follows a "walk" where a is non-decreasing? Actually a can only increase, never decrease; b can only decrease, never increase. So as we move along the sequence, a is non-decreasing and b is non-increasing. That means the sequence sorted by increasing a (or decreasing b) may have a partial order. But not strictly monotonic because a can stay same while b decreases, or b can stay same while a increases. So overall, the pairs are partially ordered: if we have two numbers i and j that appear in order i before j, then we must have a_i <= a_j and b_i >= b_j. Conversely, if a_i <= a_j and b_i >= b_j, it's possible to go from i to j via some sequence of moves (increase a and decrease b appropriately) but the path must have exactly one step per number, and we need to match immediate adjacency constraints.
But we don't need to deduce the full move type; we just need to find a linear ordering such that each consecutive pair satisfies either a_j = a_i + 1, b_j = b_i OR a_j = a_i, b_j = b_i - 1.
Thus the problem reduces to: given a set of points (a,b) with the same core c, we need to order them in a Hamiltonian path where each step is a unit step either right (increase a by 1) or down (decrease b by 1). And we need to output the corresponding numbers.
We are guaranteed solution exists.
We need to find such a path for n up to 100. One approach: Because the moves are like a lattice path, the ordering corresponds to a total order that is a topological sort in the DAG of these moves. But we need a path covering all vertices exactly once, which is essentially a Hamiltonian path in a directed graph that is a subgraph of a grid.
Since n is small (100), we could construct the directed graph: for each pair (i, j) check if a_j = a_i + 1 and b_j = b_i, or a_j = a_i and b_j = b_i - 1. Then we need to find a Hamiltonian path. This is NP-hard in general, but here the special structure might make it easy.
Alternate approach: Note that the moves are only two types, and a is non-decreasing, b is non-increasing. So the order of numbers corresponds to sorting them by some combined metric. Consider the value: v = a - b? Actually note that when we do a *2 operation, a+1; b unchanged => a - b increases by 1. When we do a /3 operation, a unchanged; b-1 => a - b increases by 1 as well. Because decreasing b by 1 increases (a - b) by 1. So each operation increases (a - b) by exactly 1. Let's compute: For a step, either (a,b)->(a+1,b) => (a+1 - b) = (a-b)+1; or (a,b)->(a,b-1) => (a - (b-1)) = (a-b)+1. Indeed each operation increments the quantity d = a - b by exactly 1. So as we progress along the sequence, d increases strictly by 1 each step. Therefore, the numbers, when ordered correctly, have d values that are consecutive integers (increasing by 1). Since there are n numbers, the d values will be some contiguous set of integers: starting from some D_start, then D_start+1, ..., D_start + n-1.
Thus the key is: the sequence can be ordered such that the value (a - b) forms an arithmetic progression with difference 1. Moreover, the starting number has the smallest d, and the ending has the largest d.
So we can compute for each number its d = exponent_of_2 - exponent_of_3. Then the numbers must be arranged in increasing order of d. However, there might be multiple numbers with the same d? Could there be? Since d increases by 1 each step, there cannot be two numbers with same d in a valid sequence because we need strict increment of 1. But is it possible to have two numbers with same d in the input? The operations ensure d changes each step, so all numbers in the sequence must have distinct d. However, the input could possibly contain numbers with same d? But then a valid ordering cannot have two numbers with same d because d must increase by 1 each step and be distinct. But is it guaranteed that they are distinct? The problem says "It is guaranteed that the answer exists." That implies that in the input, all numbers must have distinct d values. But could there be duplicates? Possibly if two numbers have same d but still we can order them? Let's examine: Suppose we have two numbers with same d. Can we have a sequence where they appear consecutively? The step would require either *2 or /3, both increase d by 1. So from a number with d to next number with same d is impossible because d must increase by 1. So they cannot be adjacent. If they are separated by other numbers, d values must be strictly increasing, so if two have same d, they cannot appear in the same sequence because the values of d are monotonic increasing and step is 1, thus they must be all distinct. Therefore, input must have distinct d values. So we can rely on that.
Thus one approach: compute d for each number, then sort numbers by d ascending, and output them. But is that sufficient? Let's test with examples.
Example 1: numbers: 4,8,6,3,12,9.
Factor each:
4 = 2^2 * 3^0 => a=2,b=0 => d=2
8 = 2^3 => a=3,b=0 => d=3
6 = 23 => a=1,b=1 => d=0
3 = 3^1 => a=0,b=1 => d=-1
12 = 2^23 => a=2,b=1 => d=1
9 = 3^2 => a=0,b=2 => d=-2
Sort by d ascending: d=-2:9, d=-1:3, d=0:6, d=1:12, d=2:4, d=3:8 => sequence: 9,3,6,12,4,8. That matches output.
Example 2: 42,28,84,126.
Factor:
42 = 237? Actually 42=237 => a=1,b=1,c=7 => d=0
28 = 2^27 => a=2,b=0,c=7 => d=2
84 = 2^237 => a=2,b=1,c=7 => d=1
126 = 23^27 => a=1,b=2,c=7 => d=-1? 1-2=-1.
Wait compute properly:
42 = 2 * 3 * 7 => exponents: a=1,b=1 => d=0.
28 = 4 * 7 = 2^2 * 7 => a=2,b=0 => d=2.
84 = 43*7 = 2^2 * 3 * 7 => a=2,b=1 => d=1.
126 = 2 * 9 * 7 = 2 * 3^2 * 7 => a=1,b=2 => d=-1.
Sort by d ascending: -1:126, 0:42, 1:84, 2:28 => sequence: 126,42,84,28. That matches output.
Example 3: 10^18, 310^18. Factor out 10^18 = 2^? Actually 10^18 = (25)^18 = 2^18 * 5^18. So exponents: a=18,b=0? Wait 10^18 = (25)^18 = 2^18 * 5^18, so a=18, b=0, d=18. 310^18 = 3 * 2^18 * 5^18 = 2^18 * 3^1 * 5^18 => a=18,b=1 => d=17? Actually a=18,b=1 => d=17. So ascending d: 17 then 18 => output: 3e18, 1e18. That matches.
Thus sorting by d = exponent_of_2 - exponent_of_3 works!
But is that always sufficient? Need to verify that the sorted order indeed yields a sequence where each consecutive pair satisfies the operation condition: either prev*2 = next OR prev/3 = next.
If we only sort by d, does it guarantee that each step is either multiply by 2 or divide by 3? Let's test on random example: Suppose we have numbers with appropriate exponents such that d values are consecutive. But is the adjacency condition automatically satisfied? For two numbers i and j with d_i and d_j = d_i+1, we need either a_j = a_i + 1, b_j = b_i or a_j = a_i, b_j = b_i - 1. But could there be a scenario where d_j = d_i+1 but both a and b change in other ways? For instance, a_j = a_i+2, b_j = b_i+1 gives d_j = (a_i+2) - (b_i+1) = a_i - b_i +1 = d_i+1. But such a pair would not satisfy the allowed moves because it would require two operations. However, could such pair be present in the input? Possibly if the set includes numbers that would require multiple steps between them? But note that the sequence is a path that visits all numbers exactly once, with adjacent moves being single steps. So if we have numbers with such differences, they cannot be adjacent; there must be intermediate numbers that fill the steps. Since we are sorting by d, we are forcing an order that might put them adjacent when they shouldn't be. But does the property that d changes by 1 ensure that the adjacency condition holds? Not automatically: it only ensures that d differs by 1. But we also need that the actual exponents satisfy one of the two specific changes. So we need to check that when we sort by d, for each consecutive pair (prev, next) with d_next = d_prev+1, it also holds that either a_next = a_prev+1 and b_next = b_prev, OR a_next = a_prev and b_next = b_prev-1. Is that guaranteed by the existence of a Hamiltonian path? Possibly the structure forces that if we have a set of points on the lattice with distinct d values that are consecutive, and there exists a Hamiltonian path that goes through all points with unit steps only, then sorting by d might produce such a path. But is sorting by d always a valid path? Not necessarily. Consider an example where we have points: (a,b) pairs: (0,0) d=0; (1,1) d=0? Actually that's not distinct d. Let's find a case with distinct d but where sorting by d does not yield a valid adjacency.
We need n points all with same core c. They must be reachable from a start via moves (1,0) or (0,-1). Since moves are only these two directions, the set of points forms a "grid path" that never goes left or up. Actually the path is a monotonic path in a and b: a non-decreasing, b non-increasing. So any valid order must be a topological ordering consistent with partial order: a non-decreasing and b non-increasing. Sorting by d is not obviously consistent with that; but d = a - b. If a non-decreasing and b non-increasing, then d is non-decreasing (since both a increases and b decreases increase d). But the converse: if we sort by d ascending, will it automatically satisfy that a non-decreases and b non-increases? Not necessarily. Consider points: (a,b) = (2,0) => d=2; (0, -1) not allowed because b cannot be negative? b is exponent of 3, so b >= 0. So b nonnegative. But could we have (a1,b1) = (0,2) d=-2; (a2,b2) = (1,0) d=1; (a3,b3) = (2,1) d=1? That doesn't have distinct d. Need distinct d.
Let's attempt to construct a counterexample. Suppose we have three numbers with (a,b): A=(0,2) d=-2; B=(1,0) d=1; C=(2,1) d=1? Not distinct. Need distinct d: -2, -1, 0, etc. For three numbers, we need d values like -1,0,1. Suppose we have points: P1 = (0,1) d=-1; P2 = (2,2) d=0; P3 = (1,0) d=1. d's are -1,0,1 and distinct. But does there exist a Hamiltonian path with unit steps covering all three? Let's check possible moves: from P1 to P2: need either (a+1,b) = (1,1) (not P2) or (a,b-1) = (0,0) (not P2). So not adjacent. From P2 to P3: need (a+1,b) = (3,2) no; (a,b-1) = (2,1) not (1,0). So not adjacent. From P1 to P3: need (a+1,b) = (1,1) no; (a,b-1) = (0,0) no. So no adjacency at all! So this set cannot be a valid sequence. So existence of solution ensures such a pathological set cannot be given.
But could there be a valid set where sorting by d does not yield a valid adjacency? That would mean there are multiple ways to order the points consistent with monotonic moves, but the sorting by d produces an ordering that does not respect the immediate step condition. However, if a set is valid, there is at least one Hamiltonian path. The question: does sorting by d always produce a valid Hamiltonian path? Let's think.
We know each step increases d by 1. Therefore, in any valid ordering, the sequence of d values is strictly increasing by 1, starting from some base. Since all d are distinct and consecutive integers, there is exactly one possible ordering by d: the increasing order. That ordering must be the order of the valid sequence. Because d increases by exactly 1 each step, so the order of d is forced. So the valid sequence must be sorted by d ascending. Therefore, the unique ordering that can work is the increasing d order. Thus, sorting by d is necessary. Since a solution exists, sorting by d must yield the correct order. So we can just sort by d and output.
But wait: Could there be two numbers with the same d? As argued, no, because then d wouldn't increase by 1 each step if they appear both; they'd have to have different d because the increments are exactly 1, and the start and end d differ by n-1. If there were two numbers with the same d, you'd have at most n-1 distinct d values, so by pigeonhole, at least two have same d. But then the sequence would have to have that d value appear twice. However, the step always increments d, so d must strictly increase; it can't stay same or decrease. So two occurrences of same d cannot happen. Therefore, all d are distinct. So sorting by d yields a unique order.
Now, we need to check that sorting by d indeed yields the correct adjacency, i.e., for each consecutive pair in sorted order, the condition holds: either a differs by +1 with b same, or a same with b differ by -1. Is it possible that sorted by d yields pairs that don't satisfy this, even though some other ordering does? Since d sorted order is forced, if sorted by d fails the adjacency condition, then no ordering can satisfy the condition because any valid ordering must have increasing d. So existence of a solution implies that sorting by d must produce a valid sequence. Therefore, sorting by d is both necessary and sufficient.
Thus algorithm: For each a_i, compute its "core" c after removing all factors of 2 and 3. Actually we don't need to compute c explicitly; we just need to confirm that all numbers share the same core; but it's guaranteed that answer exists, so we can assume it, but to be safe we can compute it and ensure consistency.
But we must be careful: numbers can be up to 3*10^18, which fits into 64-bit (2^63-1 is about 9e18). So we can use 128-bit? Actually 3e18 fits in 64-bit signed? 2^63-1 = 9.22e18, so yes, fits in signed 64-bit (int64_t). So we can use long long in C++.
Compute for each number: exponent of 2: while divisible by 2, count and divide; exponent of 3 similarly. Then compute d = cnt2 - cnt3. Also compute the remaining part after removing 2 and 3 (i.e., the core). All cores must be equal; else no solution, but problem guarantees answer exists.
Then sort the numbers by d ascending. Output them in that order.
But is it always that simple? Let's test with more cases: Suppose numbers are: 6 (23), 12 (43), 24 (83), 8. Let's see: 6: a=1,b=1 d=0; 12: a=2,b=1 d=1; 24: a=3,b=1 d=2; 8: a=3,b=0 d=3? Actually 8: a=3,b=0 d=3. So sorted d: 6(d0),12(d1),24(d2),8(d3). Check adjacency: 6->12: 12 = 62? 62=12 yes; 12->24: 122=24 yes; 24->8: 24/3=8? 24/3=8 yes. Works.
Another: 9 (3^2), 3, 6, 12, 24, 48, 96? Wait 96/3 not integer? Actually 96/3=32 not present. Let's try: 9 (a0,b2,d=-2), 3 (a0,b1,d=-1), 6 (a1,b1,d=0), 12 (a2,b1,d=1), 24 (a3,b1,d=2), 48 (a4,b1,d=3), 96 (a5,b1,d=4). Sorted by d works. Check: 48->96: *2 works; 24->48: *2 works; 12->24: *2; 6->12:*2; 3->6:*2; 9->3:/3 works. So good.
Now consider a scenario where there are both moves of type 2 and /3 interleaved. For instance, start with 12 (2^23) d=1; maybe next /3 => 4 (2^2) d=2; wait /3 reduces b by 1, so 12/3=4, d goes from 1 to 2? Actually 12: a=2,b=1,d=1; 4: a=2,b=0,d=2; d increased. Then 2 => 8 (a=3,b=0,d=3). So sequence 12,4,8. d sorted: 12(d1),4(d2),8(d3). Check adjacency: 12->4: 12/3=4 yes; 4->8: 42=8 yes. So sorted by d works.
What about a more complex: 18 (23^2) d=-1? Actually 18: a=1,b=2,d=-1; 6 (23) d=0; 12 (4*3) d=1; 4 (4) d=2; 8 d=3; sorted: 18,6,12,4,8. Check: 18->6: 18/3=6 yes; 6->12:*2 yes; 12->4:/3 yes; 4->8:*2 yes. Works.
Thus sorting by d seems to always yield a valid order.
But we must be careful about the possibility of numbers with the same core but different c? Actually core c is the part after removing all factors of 2 and 3. If two numbers have different c, they cannot be in the same sequence because operations only multiply/divide by 2 and 3, they never change other prime factors. So all numbers must share the same c. Problem guarantee answer exists, so they do.
Thus the algorithm is straightforward: compute d for each number, sort by d, output.
But there is a nuance: How to compute d for numbers up to 3e18? We can just loop dividing by 2 and 3. That's fine: worst case number is 2^? Actually 3e18, dividing by 2 repeatedly up to about log2(3e18) ~ 62 steps, similarly for 3. So overall O(n * log(a)), fine.
Now, we need to handle sorting when two numbers have the same d? But as argued, they shouldn't, but if they do, sorting by d would arbitrarily order them and might not satisfy adjacency. However, problem guarantee answer exists, so we can assume distinct d. But what if some numbers have same d but still a valid ordering exists? Let's examine if that's possible. Suppose we have numbers with same d. Since each step increases d by 1, if two numbers have same d, they cannot both appear in the sequence because then the d value would have to increase from the first occurrence to the second, but it would need to go from d to d+1 then eventually back to d? But the sequence is strictly increasing in d, so it cannot repeat a d. So indeed impossible. Therefore if input contains two numbers with same d, no solution exists, but problem guarantees answer exists, so not a concern.
Thus the solution is simply sort by exponent difference.
Implementation details:
-
Read n and array a[0..n-1].
-
For each a[i], compute:
cnt2 = 0, cnt3 = 0.
temp = a[i]
while temp % 2 == 0: temp /= 2; cnt2++
while temp % 3 == 0: temp /= 3; cnt3++
core = temp (after removing all 2 and 3)
d = cnt2 - cnt3
-
Also store core.
-
Check that all cores are equal? Actually we don't need to output if not, but we can assert or just ignore. For safety, we could verify; if not equal, then maybe the answer doesn't exist, but guaranteed so fine.
-
Sort the indices (or pairs) by d ascending.
-
Output numbers in that order.
Potential pitfalls: Sorting by d could be done using a custom comparator on pairs (d, value) or we could compute d and sort the objects accordingly.
But we need to be careful: There might be ties in d (shouldn't) but if there are, sorting by d might not guarantee correct adjacency; however, as argued it cannot happen. But to be robust, we could handle ties by some secondary criteria, but not needed.
Now, is there any edge case where sorting by d alone gives a wrong order? Let's think about the condition of adjacency: For consecutive numbers in sorted order, we need that either the next number is twice the previous OR previous is three times the next? Wait condition: next number is either previous * 2 OR previous / 3. But note that if it is previous / 3, then previous must be divisible by 3 and the result is previous/3. So the condition is not symmetric; we need to ensure that the previous and next satisfy one of these. In sorted order, we have d increasing by 1. For a pair (prev, next) with d_next = d_prev+1, there are two possibilities: either a_next = a_prev+1 and b_next = b_prev, or a_next = a_prev and b_next = b_prev-1. If both conditions could hold? Possibly if both changes? That would require a+1 and b-1 simultaneously, but that would change d by 2, so not. So exactly one of these must hold if they are adjacent in the actual sequence.
Now, could it happen that for some pair with d difference 1, neither condition holds, yet they are forced to be adjacent in sorted order? Suppose we have points: prev (a=0,b=2) d=-2; next (a=2,b=1) d=1? That's difference 3, not 1. Need difference 1: e.g., prev (a=0,b=2) d=-2; next (a=1,b=0) d=1? Actually 1 - 0 = 1, d diff = 3? Let's compute: d_prev = 0-2 = -2; d_next = 1-0 = 1; diff = 3. So not.
We need d diff =1: So if prev (a1,b1), next (a2,b2) such that a2 - b2 = a1 - b1 + 1. That does not guarantee that either a2=a1+1,b2=b1 or a2=a1,b2=b1-1. Because the equation is a2 - b2 = a1 - b1 + 1 => (a2 - a1) - (b2 - b1) = 1. There are many integer solutions where a2>=a1? Actually in a valid sequence, we must have a2 >= a1 and b2 <= b1 because a is non-decreasing and b non-increasing along the path. However, in the sorted order, we haven't enforced that a and b individually have monotonic behavior; we only enforce d ascending. But if the set is from a valid sequence, then any valid ordering must also respect the monotonicity of a and b? Actually yes, because in the actual sequence, each step either increases a by 1 (and b unchanged) or decreases b by 1 (and a unchanged). So overall, along the sequence, a never decreases, b never increases. Therefore, for any two numbers that appear in the sequence (not necessarily adjacent), if the first appears earlier than the second, then a(first) <= a(second) and b(first) >= b(second). This is a necessary condition for the ordering. So in particular, for the entire ordering (which is the valid sequence), we must have that the sorted-by-d order also satisfies that a is non-decreasing and b is non-increasing. Because d is increasing, but does that force a non-decreasing and b non-increasing? Not necessarily; it's possible to have a decreasing and b decreasing more such that d increases. For example, from (a=2,b=0) d=2 to (a=1,b=-1) d=2? Actually b cannot be negative because it's exponent of 3, so b>=0. But consider (a=2,b=0) d=2; (a=1,b=0) d=1; that's decreasing d. So not. For increasing d, we could have a decrease and b decrease even more: Suppose (a=5,b=2) d=3; (a=4,b=0) d=4. Here a decreased by 1, b decreased by 2. d increased by 1. But does such a pair satisfy the allowed adjacency? No, because to go from (5,2) to (4,0), you'd need to decrease a by 1 and decrease b by 2, which would require at least two steps. However, could they be in the same set if there exists a number in between that fills? Possibly if we have intermediate points: (5,2) ->? Let's see: we need to decrease b by 2 and a by 1, we could do: (5,2) -> (5,1) via /3, then (5,1) ->? to get to (4,0) we need either decrease a? But decreasing a is not allowed. So we cannot decrease a at all. Actually operations never decrease a. So a is non-decreasing. So in any valid sequence, a can never decrease. Similarly, b can never increase. Therefore, for any two numbers in the sequence (with order preserved), we must have a(prev) <= a(next) and b(prev) >= b(next). So the ordering must be consistent with these partial orders.
Now, consider two numbers that are not adjacent but appear in the sorted order (by d) perhaps violating these monotonicities. For the sorted order to be a valid sequence, it must satisfy these monotonicities. So if sorted order fails to have non-decreasing a or non-increasing b, then it cannot be the valid sequence. But could there be a set where sorted order fails monotonicity but a different ordering (still increasing d) exists? Since d is strictly increasing, any ordering that respects d increasing must be the unique order of d values; because d values are distinct and increasing, they impose a total order: we must place lower d before higher d. So the ordering is forced: it's exactly the sorted by d order. There's no freedom to reorder numbers with same d because they are distinct. So the only possible ordering that respects d increasing is the sorted order. Therefore, if sorted order does not satisfy monotonicity of a and b, then no valid sequence exists. Since existence is guaranteed, sorted order must satisfy a non-decreasing and b non-increasing.
Thus we can rely on sorting by d.
Now we can implement with confidence.
But we need to be careful: compute d = cnt2 - cnt3. This could be negative. Sorting ascending is fine.
Potential issues: large numbers, division loops. Use long long in C++.
Check: all numbers must have same core. Could there be numbers with different core but still possible because operations could be applied that change core? No, because only multiplication/division by 2 or 3, cannot affect other prime factors. So core must be same. Problem guarantee.
Now implement.
One more nuance: The input numbers can be as large as 3e18, which is within 2^62? Actually 2^62 is about 4.6e18, so 3e18 fits. But careful: when we divide by 2 repeatedly, we might have odd numbers; but 3e18 is even? Anyway fine.
Now think about potential integer overflow during core computation? We are just dividing the number by 2 and 3 until not divisible, storing the remainder. That's safe.
Now provide solution in Python? Actually user asked "Write code". We can produce solution in C++? But typical competitive programming solutions are in C++. Let's assume they want C++.
Implementation steps:
-
Read n.
-
Create a vector of struct { long long val; long long d; long long core; } maybe not needed.
-
For each input number x:
cnt2 = 0, cnt3 = 0;
temp = x;
while(temp % 2 == 0){ temp /= 2; cnt2++; }
while(temp % 3 == 0){ temp /= 3; cnt3++; }
d = cnt2 - cnt3;
core = temp;
store (val, d, core) or just val and d.
Also store the first core to compare with others: ensure all cores equal.
-
After reading all, sort the array by d ascending.
-
Output sorted values.
But we must ensure that sorting by d yields a valid sequence? Could there be ties? If ties occur, we might need to order them in a way that respects operations? But as argued, ties can't exist if answer exists. But if they do exist due to input error, we might need to handle? But problem guarantee answer exists, so fine.
Thus final solution.
But I recall that some solutions for this problem (Codeforces 371C) do exactly that: sort by exponent difference. So it's correct.
Double-check with some random cases I can think.
Case: n=2, numbers 2 and 3? 2: a=1,b=0,d=1; 3: a=0,b=1,d=-1. Sorted: 3,2. Check: 32=6 not 2; 3/3=1 not 2; 2/3 not integer; 22=4 not 3. So 2 and 3 cannot be a valid pair. But does problem guarantee answer exists, so such input won't appear.
Case: 4 and 6? 4:d=2;6:d=0; sorted:6,4. Check:6/3=2 not 4;6*2=12 not 4. So not valid. So input wouldn't have that.
Thus algorithm.
Now, what about if the core is not the same? Example: 5 and 10? 5: core=5,d=0; 10: core=5? Actually 10=25 => after removing 2, core=5. So core same. 5 and 15? 15=35 core=5; d:5:d=0;15:d=-1? 15: a=0,b=1 => d=-1. Sorted:15,5. Check:15/3=5 works! So it's fine. So core same indeed.
Now, consider numbers like 6 (23) and 10 (25) core differ, can't be in same sequence.
Thus all good.
Now, we can produce the code.
Edge Cases:
-
n up to 100, but numbers up to 3e18. We should use unsigned long long? long long sufficient, but careful when dividing by 2 or 3, it's integer division; fine.
-
The core may be large, but we only need to compare with other cores. Use long long.
Now implement.
I'll produce a C++ solution.
Pseudo-code:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct Num {
ll val;
ll d;
ll core; // might not need
};
int main() {
int n;
cin >> n;
vector a(n);
ll common_core = -1;
for (int i = 0; i < n; ++i) {
ll x;
cin >> x;
ll cnt2 = 0, cnt3 = 0;
ll temp = x;
while (temp % 2 == 0) { temp /= 2; cnt2++; }
while (temp % 3 == 0) { temp /= 3; cnt3++; }
ll d = cnt2 - cnt3;
ll core = temp;
a[i] = {x, d, core};
if (i == 0) common_core = core;
else if (core != common_core) {
// According to problem guarantee, this won't happen.
// But we could still accept if core same? Actually we might need to handle.
}
}
sort(a.begin(), a.end(), [](const Num& p, const Num& q) {
return p.d < q.d;
});
for (int i = 0; i < n; ++i) {
cout << a[i].val << " ";
}
cout << endl;
return 0;
}
That should work.
But is there any scenario where sorting by d alone gives the wrong order due to same d? Not possible.
Thus answer.
But wait, there is nuance: The difference d = exponent_of_2 - exponent_of_3 increases by exactly 1 each step. However, the starting number could have the smallest d and the final the largest. So sorted by d ascending yields the order. So that is the solution.
Now, but we need to be careful: The numbers might be large; but sorting is fine.
Thus final solution.
Let's produce final answer with explanation.
Also, we can include additional check: After sorting, we could optionally verify adjacency to be safe, but not needed.
Now, I'll write a solution in Python? The problem might be expecting C++. However, typical Codeforces solutions are in C++. But I can provide both? The user didn't specify language; they said "Write code". Usually they expect code in a common language like C++. But I can produce Python as well. However, given the constraints, Python is fine. But handling large numbers up to 3e18 is fine in Python. But the input reading and loops are fine. But we need to be mindful of speed: n <= 100, fine.
But I think the usual answer is C++.
Nevertheless, I'll produce solution in C++.
Now, I'll output the final answer with code and explanation.
But the user asked "think step by step", then "output the final answer". Already did step by step reasoning. Now produce final code.
Potential improvements: Instead of storing core, we could just compute d and sort.
Simplify: For each number, compute d, store in pair, sort by d.
Now, code:
#include
#include
#include
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<long long, long long>> arr; // (d, value)
long long common_core = -1;
for (int i = 0; i < n; ++i) {
long long x;
cin >> x;
long long temp = x;
int cnt2 = 0, cnt3 = 0;
while (temp % 2 == 0) {
temp /= 2;
++cnt2;
}
while (temp % 3 == 0) {
temp /= 3;
++cnt3;
}
long long core = temp;
if (i == 0) common_core = core;
// else assert(core == common_core);
long long d = cnt2 - cnt3;
arr.push_back({d, x});
}
sort(arr.begin(), arr.end());
for (auto &p : arr) {
cout << p.second << " ";
}
cout << endl;
return 0;
}
That's it.
Potential issue: In sorting, we used pair with first=d, second=value; sorting pairs by first ascending then second ascending. That's fine; if d ties, they'll be sorted by value, but ties shouldn't occur.
Thus final answer.
Now, I'll produce final output with the code.
But also could use stable sort.
Now final. ```cpp
#include
#include
#include
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<long long, long long>> a; // (d, value)
for (int i = 0; i < n; ++i) {
long long x;
cin >> x;
long long temp = x;
int cnt2 = 0, cnt3 = 0;
while (temp % 2 == 0) {
temp /= 2;
++cnt2;
}
while (temp % 3 == 0) {
temp /= 3;
++cnt3;
}
// temp now is the part not divisible by 2 or 3 (the "core")
// It is guaranteed to be the same for all numbers (by problem statement)
long long d = cnt2 - cnt3;
a.push_back({d, x});
}
sort(a.begin(), a.end()); // sort by d ascending
for (auto& p : a) {
cout << p.second << " ";
}
cout << endl;
return 0;
}