We are given the GCD table G of size n x n for an array a of positive integers length n. The table G[i][j] = gcd(a_i, a_j). So the table is symmetric and has diagonal entries G[i][i] = a_i. Actually gcd(a_i, a_i) = a_i. So the diagonal entries are the original numbers. However, note that the input gives all numbers from the table in an arbitrary order. We need to reconstruct the array a.
Given all gcd pairs (including i=j), we have n^2 numbers, including the original numbers (the diagonals) but also off-diagonal gcds. Since it's symmetric, each pair appears twice (or once if we count each entry). But the input includes all n^2 numbers. They are given as multiset of n^2 numbers. We need to find array a of length n such that the multiset of gcd(a_i, a_j) (for i, j in [1..n]) matches the input multiset (as a multiset). It is guaranteed that the input corresponds to some a.
We need to reconstruct a.
We can think of it as: we are given a multiset S of size n^2 containing numbers. Let the unknown array a be sorted? Not necessarily but we can maybe reconstruct.
Observation: The diagonal entries are the largest numbers in each row? Actually for any i, j: gcd(a_i, a_j) <= min(a_i, a_j). So a_i appears as G[i][i] which is equal to a_i. It may appear elsewhere if there is another number that is a multiple of a_i? Actually gcd(a_i, a_j) could be equal to a_i if a_i divides a_j. So a_i could appear many times. But generally, the numbers in the array a are among the input numbers, but not all input numbers correspond to a_i because the diagonals are exactly the a_i. However, off-diagonals can be equal to some a_i as well.
But we can think of constructing the array using a method: The multiset S contains all gcd pairs. If we sort the numbers descending, the largest number must be the maximum element of a, because gcd of any two numbers cannot exceed either number, so the maximum gcd in the table is max(a_i) (since the diagonal entry for the max a_i gives that value). Actually if max a_i is M, then G[i][i] = M for that i. Off-diagonal entries with that i could be gcd(M, a_j) which may be less than M. So the maximum number in the multiset is indeed M. However, could there be another number equal to M that is not the diagonal? For that to happen, we would need gcd(a_i, a_j) = M, which implies both a_i and a_j are multiples of M, so a_i >= M, a_j >= M, and since M is the maximum, a_i = M and a_j = M (or both equal M). So it could appear off-diagonal only if there are two elements both equal to M (then gcd(M, M) = M). So if M appears k times in a (i.e., there are k copies of M), then in the table, the number M appears at least k times on the diagonal for those indices, plus off-diagonal between each pair of those indices: for i != j among those k indices, gcd(M, M) = M. So total occurrences of M in the table would be k^2 (since all pairs among those indices give M). So the count of the maximum value can indicate the multiplicity.
This suggests an approach: We can start from the multiset of given numbers, sort them descending. The largest number x must be in a. Moreover, its frequency in the multiset tells us how many times it appears in a (i.e., its count in a). Actually careful: If we have a multiset of n^2 gcd values, the frequency of a value v is sum over pairs (i,j) such that gcd(a_i, a_j)=v. So for v being the maximum element (M), as argued, only pairs where both numbers are multiples of M and at least M can give gcd M. Since M is the max, only numbers equal to M can produce gcd M. Let k = number of indices i with a_i = M. Then any pair (i,j) both from these k indices gives gcd = M. So total count of M in S is k^2. So we can compute k = sqrt(freq(M)). That must be integer. Then we can take that many copies of M into answer.
Now we remove all those k^2 entries from S (or decrement frequencies). Then we consider the next largest number. But careful: After removing the contributions from the M-copies, the remaining numbers correspond to gcds that do not involve both indices being among the M copies? Actually they involve at least one index not from the M-copies. But we need to systematically build the array.
I recall a known problem: "GCD Table" from Codeforces (maybe problem 582A? Actually there is problem "GCD Table" 582A? Let's check memory: There is Codeforces Round #322 (Div. 2) problem "GCD Table" 583B? No. Actually there is problem "GCD Table" from Codeforces: "582A GCD Table". Yes, I think that's it: Given the multiset of n^2 gcds, reconstruct the array. The solution involves using a multiset, repeatedly taking the largest remaining number, knowing its count in the current multiset corresponds to the number of times it appears as gcd among the remaining elements (i.e., the yet-to-be-determined numbers). The typical solution: Maintain a multiset of all numbers. Also maintain a list of already found numbers (the array a). Initially empty. While multiset not empty: Take the largest value x present. Its frequency f in the current multiset must correspond to the number of times it appears as gcd among the yet-to-be-chosen numbers and between chosen and unchosen? Actually typical solution: Start with an empty list ans. At each step, take the largest number from the multiset. Let its current count be c. Since ans already contains some numbers, we must consider that x appears not only from gcds among the new numbers we will add but also from gcds between new numbers and already chosen ones? Wait.
Better to recall known solution: In many editorial solutions, they maintain a multiset of the given numbers. They also maintain a list of answer elements. They take the largest number from the multiset, add it to answer, and remove that occurrence. Then for each y in the current answer (including the newly added one), they compute gcd(x, y) and remove two occurrences? Actually because the table is symmetric? Let's derive.
Given we have the full multiset of all gcd(a_i, a_j) for i,j. If we are constructing the answer by gradually picking numbers from the multiset, we need to account that when we add a new number to the answer, the gcds between that new number and previously added numbers, as well as gcd of the new number with itself, have already been included in the original multiset. But if we are removing numbers as we build, we need to subtract those contributions to reflect the remaining numbers that correspond to gcds among the yet-to-be-chosen numbers? Hmm.
Alternative method: There is known algorithm: sort the given numbers descending. Use a frequency map. Maintain a list ans. For each number in sorted order (largest to smallest), if its frequency > 0, then we include it in ans, and then for each already found number y in ans, we compute gcd(x, y) and subtract 2 from its frequency (because gcd(x,y) appears twice? Actually need to think carefully.
But let's reason from first principles.
We have an array a of length n. The multiset S contains all values d_{i,j} = gcd(a_i, a_j). This is symmetric: for i != j, each unordered pair (i,j) contributes two entries (i,j) and (j,i) unless we consider the table includes both. Since they give the same gcd, the multiplicity of each value is sum over ordered pairs.
We are given S as a multiset. We need to find a.
Observation: The numbers a_i themselves are present in S as diagonal entries, but also possibly off-diagonal if divisibility.
But we can treat the construction as: We will determine the array elements one by one, each time taking the largest remaining number from S, and then removing all gcd contributions that involve that element with already selected elements and with itself. However, we need to be careful: Since we are selecting elements from the multiset that correspond to actual array elements, we need to ensure that when we pick a number x from S, we know that x is actually an element of a. The largest remaining number in S is indeed an element of a, because any gcd cannot be larger than the largest array element, and the largest array element appears as diagonal entry; also after we remove contributions of that largest element and its interactions with others, the next largest remaining number might be another element of a or could be a gcd that is not an element of a but still large. For example, consider array [6, 10]. The gcd table entries: (6,6)=6, (6,10)=2, (10,6)=2, (10,10)=10. Sorted: 10,6,2,2. The largest is 10, which is element. After removing 10 and its interactions? If we just take 10 and remove one occurrence of 10 from S, we get S:6,2,2. The next largest is 6, which is element. Then we need to remove gcd(6,10)=2 two times? Actually when we have ans = [10], then we want to add 6. But we need to account that gcd(6,10)=2 appears in S. However, if we have not removed those occurrences before, when we later consider 6, we need to ensure that the count of 2 is correct. The known algorithm does: Start with empty ans and multiset of all numbers. While multiset not empty:
let x = largest number in multiset.
For each y in ans:
let g = gcd(x, y)
remove two occurrences of g from multiset? Actually remove one? Since table includes ordered pairs, for each unordered pair {i,j}, there are two entries: (i,j) and (j,i). So the contribution of gcd(a_i,a_j) to the multiset is 2 for i != j, and 1 for i=j (since (i,i) appears once? Actually the table is n x n, so it includes all ordered pairs. So diagonal entries are just once each, off-diagonal entries are two each (i,j) and (j,i). In the input, they give n^2 numbers. So it includes each ordered pair. So for i != j, there are two identical entries: gcd(a_i,a_j) appears twice. For i=j, it appears once.
Thus, the multiset S contains each unordered pair's gcd value twice (except when i=j, once). So the total count of each value v is: sum_{i} [a_i = v] (diagonal) + 2 * sum_{i<j} [gcd(a_i,a_j) = v].
Now, if we are building ans incrementally, we need to subtract contributions as we add a new element.
Suppose we have already determined some set of elements that will be part of the final array (say we have selected some indices). But we are not distinguishing which indices. The approach: We can start with an empty list ans. We maintain a multiset (or frequency map) of the remaining numbers from S. At each step, we pick the largest number x from the multiset (with frequency >0). We know that x must be one of the array elements because: If x were not an array element, then it must be a gcd of two numbers. But then those two numbers are at most x (since gcd <= each), and if they are less than x, then the maximum number in the whole table would be max(array) which is > x? Not necessarily: Suppose array = [6, 8, 12]. The max is 12. The largest gcd could be 12 from diagonal, then 8? Actually gcd(8,12)=4. So 8 is an array element, appears as diagonal, so it's present. The next largest after 12 is 8? Actually array elements: 12,8,6. So they all appear as diagonals. So the largest number left after removing 12 is 8, which is an element. Could there be a case where a non-element number is larger than some element? For example, array = [6, 10, 15]. Sorted: 15,10,6. gcd(10,15)=5, gcd(6,10)=2, gcd(6,15)=3. So the numbers: 15,10,6,5,3,2, plus repetitions? Actually diagonal: 15,10,6; off-diagonals: gcd(10,15)=5 appears twice, gcd(6,15)=3 twice, gcd(6,10)=2 twice. So multiset: 15,10,6,5,5,3,3,2,2. Sorted: 15,10,6,5,5,3,3,2,2. The largest is 15 (element), then 10 (element), then 6 (element). So all elements appear before non-elements. But what if an element is smaller than some gcd? Could a gcd be larger than some array element? Suppose a = [6, 8]. Then gcd(6,8)=2, which is less than both. So gcd <= min. So any gcd is at most the minimum of the two numbers. So it's always less than or equal to each of the two numbers. Therefore, the largest numbers in the multiset are the largest array elements, because any gcd cannot exceed the numbers, and the diagonal entries give the numbers themselves. So the largest number overall is the maximum array element. The second largest could be either the second largest array element or a gcd that is equal to the second largest if that second largest is a divisor of the largest? Actually if the largest number M1, and second largest M2, could there be a gcd(M1, something) that is larger than M2? Suppose M1=12, M2=5, but maybe we have a third element 6? Actually gcd(12,6)=6, which is larger than 5. So then 6 > 5. But 6 is itself an array element if we have 6. So it's still an element. But if we don't have 6, can a gcd be greater than some array element? For array [12,5], gcd(12,5)=1. So no. For array [12,8,5], gcd(12,8)=4 which is less than 5? Actually 4<5. So largest after 12 is 8 (element), then 5 (element), then 4 (gcd), etc. So it seems that all array elements are among the top n largest numbers? Not necessarily, consider array with many small elements and one large. The small elements themselves may be small, but there could be gcds among larger elements that are larger than some small element? Let's test: a = [12, 6, 4]. Largest: 12, next 6, next 4. gcd(12,6)=6, which equals 6 (an element). gcd(12,4)=4, equals 4. gcd(6,4)=2, which is smaller than 4. So the sorted list: 12,6,6,4,4,2,2? Actually table includes: (12,12)=12, (12,6)=6 (twice), (12,4)=4 (twice), (6,6)=6, (6,4)=2 (twice), (4,4)=4. So multiset: 12,6,6,6,4,4,4,2,2. Sorted: 12,6,6,6,4,4,4,2,2. The array elements: 12,6,4. They appear among the top values, but note that 6 appears three times (more than once) and 4 appears three times. But there is no value between 6 and 4 that is not an element. The third largest distinct value is 4, which is an element. So far okay.
Consider a case: a = [6, 10, 15] we saw all elements appear as top distinct values. What about a = [6, 9, 15]? Let's compute: elements: 15,9,6. gcd(15,9)=3, gcd(15,6)=3, gcd(9,6)=3. So table: diagonals: 15,9,6; off-diagonals: each gcd=3 appears twice for each pair: total 6 entries of 3? Actually three pairs: (15,9), (15,6), (9,6). Each pair gives two ordered entries, so 6 entries of 3. So multiset: 15,9,6,3,3,3,3,3,3. Sorted: 15,9,6,3,... Here 3 is not an element. So the top three numbers are 15,9,6 which are elements. So yes.
Now consider a case where an element is not among the top n numbers by value? For instance, if we have many elements, and some elements are very small, while some gcds between large numbers could be large, possibly exceeding some small elements. But gcd of two large numbers could be as large as the smaller of the two. So it is at most the smaller of the two numbers. If we have a large set, the smallest element is small. Could there be a gcd that is larger than the smallest element? Possibly yes, because gcd of two numbers both larger than the smallest could be greater than the smallest. For example, a = [100, 50, 3]. Then elements: 100,50,3. gcd(100,50)=50, which is >3. So 3 is the smallest element. The sorted multiset: 100,50,50,50? Let's compute: diagonal: 100,50,3. Off-diagonal: (100,50)=50 (twice), (100,3)=1 (twice), (50,3)=1 (twice). So multiset: 100,50,3,50,50,1,1,1,1? Wait careful: (100,50) gives two 50s, (100,3) gives two 1s, (50,3) gives two 1s. Also (50,100) already counted? Actually ordered pairs: we have (100,50) and (50,100) both 50, that's two 50s; (100,3) and (3,100) two 1s; (50,3) and (3,50) two 1s. So total: 100,50,3, 50,50, 1,1,1,1? That sums to 3 (diagonals) + 2+2+2 = 9 entries. So the list: 100, 50, 50, 50, 3, 1,1,1,1? Actually 50 appears: one from diagonal (a2=50), plus two from (100,50) and (50,100) = two, total three 50s. 1 appears four times. So sorted: 100,50,50,50,3,1,1,1,1. The top three distinct values: 100,50,3. So the smallest element 3 is among the top three distinct values? There are only three distinct values: 100,50,3. So it's present. But if we have more elements, say n=4: a = [100, 50, 6, 3]. Compute: elements: 100,50,6,3. gcd(100,50)=50, (100,6)=2, (100,3)=1, (50,6)=2, (50,3)=1, (6,3)=3? Actually gcd(6,3)=3. So table: diagonals:100,50,6,3. Off-diagonals: (100,50)=50 twice, (100,6)=2 twice, (100,3)=1 twice, (50,6)=2 twice, (50,3)=1 twice, (6,3)=3 twice. So multiset: 100,50,6,3, 50,50, 2,2, 1,1, 2,2, 1,1, 3,3. Combine: 100(1), 50(1+2=3), 6(1), 3(1+2=3), 2(2+2=4), 1(2+2=4). Sorted distinct: 100,50,6,3,2,1. The elements are 100,50,6,3. The smallest element 3 is still among top 4 distinct? Actually top 4 distinct values: 100,50,6,3. That's exactly the elements. But could there be a case where an element is not among top n distinct values? Suppose we have many elements with repeated values? But distinctness aside, the array elements themselves are present in the multiset, but they might not be the largest n numbers if there are many large gcd values that are larger than some small element? For example, consider array: [8,12,6,10]. Largest:12,10,8,6. Compute gcds: gcd(12,8)=4, gcd(12,6)=6, gcd(12,10)=2, gcd(8,6)=2, gcd(8,10)=2, gcd(6,10)=2. So table: diagonals:12,10,8,6. Off-diagonals: (12,8)=4 twice, (12,6)=6 twice, (12,10)=2 twice, (8,6)=2 twice, (8,10)=2 twice, (6,10)=2 twice. So multiset counts: 12(1),10(1),8(1),6(1+2=3) because (12,6) gives two 6s, so total 1+2=3. 4 appears twice, 2 appears (2+2+2+2)=8? Actually (12,10)=2 twice, (8,6)=2 twice, (8,10)=2 twice, (6,10)=2 twice => total 8. So sorted list (including duplicates): 12,10,8,6,6,6,4,4,2,... The top numbers (distinct): 12,10,8,6. So elements. If we take the top n numbers by value (ignoring duplicates), we get the elements? But what about a case like a=[6,10,15] we saw distinct values:15,10,6,5,3,2? Actually we have 3 elements, distinct values: 15,10,6,5,3? Wait we have 3 elements: 15,10,6. The distinct gcds: 15,10,6,5,3,2? Actually gcd(10,6)=2, gcd(15,6)=3, gcd(15,10)=5. So distinct: 15,10,6,5,3,2. So top 3 distinct are 15,10,6. That works.
Consider a case where some element is repeated, e.g., a = [6,6,6]. Then table: all entries are 6. Multiset: 6 appears 9 times. The largest number is 6, and the top three numbers (if we take distinct) we only have 6. But we need to know that there are three copies. So we can't just take top distinct; we need multiplicity.
But the algorithm that picks the largest remaining and then subtracts contributions works for repeated elements as well.
Let's reason about the algorithm that is known: We maintain a multiset (counter) of all numbers. We also maintain a list answer. While the multiset is not empty:
Let x be the greatest number in the multiset (with current count >0).
For each y in answer:
remove gcd(x, y) twice? Or once? Actually typical solution from editorial: When we pick x, we need to account that the gcds between x and the previously chosen numbers have already been counted in the multiset. But we are constructing the array; when we add x to answer, we must remove its contributions with already chosen numbers, because those contributions correspond to pairs that involve x and earlier chosen numbers. Since we have already removed contributions from pairs among earlier chosen numbers, the remaining multiset should represent the contributions of pairs that involve at least one of the yet-to-be-chosen numbers? Wait, we need to be careful about the order of removal.
We have original multiset S containing all ordered pairs. If we are building the answer incrementally, we can think of selecting one element at a time, and for each selected element, we remove from S all entries that correspond to pairs between this element and any element already selected, as well as the self-pair of this element. Then the remaining multiset corresponds to the pairs among the remaining (not yet selected) elements. However, note that pairs between the selected element and yet-unselected elements should also be removed, but we don't know those elements yet. So we cannot remove those yet. So the above approach would only remove pairs among selected elements, but then the remaining multiset would still contain pairs between selected and unselected, as well as unselected-unselected. That would cause trouble because when we later pick an unselected element, its self-pair and interactions with already selected will still be present. So we need to remove them at the time we pick the element. So we can do: When we pick x (the largest remaining number), we add it to ans. Then we must remove from the multiset:
- one occurrence for the diagonal (x,x) (since we have one entry for i=j for this element).
- for each y already in ans (including possibly this x? but we treat separately), we need to remove two occurrences of gcd(x, y) because the ordered pairs (x,y) and (y,x) are present. However, note that when y = x (i.e., if we had duplicates and this is not the first copy), we need to be careful: For duplicates, the diagonal for each copy is separate. But if we already have some copies of x in ans, then we are adding another copy of x. Then we need to consider:
- The diagonal for the new copy: remove one occurrence of x.
- For each existing element y (including other copies of x), we need to remove two occurrences of gcd(x, y). For y = another copy of x, gcd(x,x)=x, so we need to remove two occurrences of x for that unordered pair? But careful: For two distinct indices i and j both equal to x (value), the table entries are: (i,i) diagonal of first gives x; (j,j) diagonal of second gives x; (i,j) gives x; (j,i) gives x. So total contributions: from the pair (i,j) with i != j, we have two entries both x. So when we add a second copy of x, we need to remove the contributions for the pairs between the new index and each existing index. This includes:
- For each existing element y (distinct index), we need to remove two copies of gcd(x,y). In particular, for y = x (i.e., a previous copy of the same value), gcd(x,x)=x, so we remove two copies of x.
Additionally, the new element's self-pair (diagonal) is one copy of x.
So overall, when we add a new element x, we should decrement the count of x by 1 (for its diagonal), and for each y in ans before adding (the existing ones), we decrement count of gcd(x,y) by 2.
But initially ans is empty. So first element: remove one occurrence of x. So we remove one x from multiset. Then we add x to ans.
Now second element: we pick the next largest number (which must be another element, but we need to verify). However, we haven't removed the interactions between the first element and the second yet. Those interactions are still present in the multiset. When we pick the second element, we will remove its diagonal (one occurrence) and also remove two occurrences of gcd(x1, x2) for each existing element (just x1). So that will remove those interactions at that time. So the multiset after processing the second element will have those interactions removed.
Thus the algorithm works if we always pick the largest remaining number, because it is guaranteed to be an element of a (since all interactions with larger elements have been removed? Let's test with example a = [6,10,15] we saw. Initially S: counts: 15:1, 10:1, 6:1, 5:2, 3:2, 2:2? Actually compute exactly: S sorted: 15,10,6,5,5,3,3,2,2. Multiplicity: 15:1,10:1,6:1,5:2,3:2,2:2.
Algorithm:
- ans=[]
- multiset = {15:1,10:1,6:1,5:2,3:2,2:2}
Pick largest: 15. Remove one occurrence of 15 -> 15:0 (so 15 removed). ans=[15].
Now next largest: currently 10 (count 1). Is 10 guaranteed to be an element? Let's see: After removing only the diagonal of 15, the interactions between 15 and others are still present. So multiset still has entries: gcd(15,10)=5 appears twice, gcd(15,6)=3 appears twice, and the diagonal of 10, and diagonal of 6, and the interaction between 10 and 6 (2 twice). So the multiset still has 10 (count 1). The largest remaining number is 10, which is indeed an element. So we pick 10. Then we need to remove its diagonal (one 10) and for each y in ans (just 15) remove two gcd(10,15)=5. So we decrement 10 by 1 -> 10 removed. Decrement 5 by 2 -> 5 count was 2, becomes 0. So now multiset: 6:1, 3:2, 2:2. ans=[15,10].
Next largest: 6 (count 1). Remove one 6 (diagonal) -> 6:0. For each y in ans (15 and 10), remove two gcd(6,15)=3 and two gcd(6,10)=2. So decrement 3 by 2 -> 3 count 2 -> 0; decrement 2 by 2 -> 2 count 2 -> 0. Multiset empty. Done. ans = [15,10,6] which matches (order not important). So algorithm works.
Now test with duplicate case: a = [6,6,6]. S: all 9 entries are 6. multiset: 6:9.
Algorithm:
- ans=[]
- pick largest 6, remove one 6 -> count 8, ans=[6].
- next largest: 6 (count 8). Remove one 6 -> count 7, then for y=6 (first element), remove two gcd(6,6)=6 -> count 7-2=5. ans=[6,6].
- next largest: 6 (count 5). Remove one 6 -> count 4, then for each y in ans (two elements): remove two 6 for each -> remove 2*2=4? Actually for y1 (first 6): remove two 6; for y2 (second 6): remove two 6; total removal 4. So count 4-4=0. Done. ans=[6,6,6]. Works.
Now test with earlier example: a = [100, 50, 6, 3]. S counts: 100:1, 50:3, 6:1, 3:3, 2:4, 1:4. (We computed earlier). Let's run algorithm:
Start: multiset with above counts.
Pick largest: 100 (count 1). Remove one 100 -> 100:0. ans=[100].
Next largest: 50 (count 3). Remove one 50 -> 50:2. For y=100, gcd(100,50)=50, remove two 50 -> 50:2-2=0. ans=[100,50]. (Now 50 count 0).
Next largest: now we have 6:1, 3:3, 2:4, 1:4. Largest is 6. Remove one 6 -> 6:0. For each y: y=100 -> gcd(6,100)=? Actually gcd(6,100)=2, remove two 2 -> 2:4-2=2. y=50 -> gcd(6,50)=2, remove two 2 -> 2:2-2=0. ans=[100,50,6].
Next largest: now we have 3:3, 1:4 (2 is 0). Largest is 3. Remove one 3 -> 3:2. For each y: y=100 -> gcd(3,100)=1, remove two 1 -> 1:4-2=2. y=50 -> gcd(3,50)=1, remove two 1 -> 1:2-2=0. y=6 -> gcd(3,6)=3, remove two 3 -> 3:2-2=0. ans=[100,50,6,3]. Done. Works.
Thus the algorithm is:
- Read n, and the n^2 numbers.
- Put them in a multiset (or better, use a frequency map, e.g., a Counter from collections, but since numbers up to 1e9 and n up to 500, we can just use a list and sort and simulate removal with a multiset using a balanced BST? But simpler: we can use a list and sort, then use a frequency map with deletions. But we need to be able to get the largest element and decrement counts. Since n is only up to 500, n^2 is up to 250k. So we can store all numbers in a list and sort descending. Then we can use a frequency counter and also maintain a list of numbers in descending order without removal but just decrement counts; we can iterate over the sorted distinct numbers in descending order. But we need to repeatedly pick the largest number with positive count. That can be done by maintaining a sorted list of keys (distinct numbers) and updating counts, but since number of distinct values could be up to 250k (maybe less), but n is small, but the numbers could be many distinct. However, we can just use a multiset implemented by a list and actual removal? But removal of arbitrary elements from a sorted list may be O(n^2) if we use list.remove. But n^2=250k, and we will perform up to n steps (max 500). In each step we might need to remove up to O(n) gcd values (for each existing element, we remove two occurrences of some number). So total removals O(n^2) = 250k. If we use a Counter (dictionary) for frequencies, and maintain a list of all numbers sorted descending, we can simply get the largest by scanning the sorted distinct list from the start to find the first with positive count. Since n is only 500, the number of distinct numbers could be up to 250k, but scanning from the start each time could be O(distinct) per step, which could be up to 250k * 500 = 125M, borderline but maybe okay in Python? 125M operations might be too slow, but we can optimize: we can maintain a max-heap (priority queue) of numbers with their frequencies, but we need to be able to update frequencies and pop the largest with positive count. Since we will be decrementing frequencies of numbers (some might become zero). We can push all distinct numbers into a max-heap (negatives for min-heap). But we need to know the current max; we can pop from heap, check if its count is still >0, if not pop again. When we decrement counts, we don't need to push new values; we just decrement. But the heap still contains the number; when we later pop, we might get a number with zero count, we skip. That's okay. The number of distinct numbers is at most n^2 = 250k, pushing all into heap is fine. Each step we pop until we find a number with positive count; overall we might pop each distinct number at most once when it's zero? Actually we might pop the same number multiple times if its count becomes zero after being popped earlier? But we will pop the number when it's the current max; after we process it, we might later decrement counts of some numbers, but they won't become the new max if they are smaller than the max we just processed? Wait the algorithm: We repeatedly take the largest number in the multiset. After processing that number (adding it to answer and removing its contributions), we then need to find the next largest number in the updated multiset. This next largest could be the same number if its count is still positive (e.g., duplicates of same value). For example, in the duplicate case, the largest number was 6, and after we processed one copy, the count of 6 decreased but still positive; the next largest is still 6. So we need to be able to get the same number again if its count remains >0. So using a heap, we could push the number again after decrement? Actually we can simply leave the number in the heap; when we pop, we get the largest number (largest value). If its count is still >0, we use it. But after we use it, we will decrement its count (by 1 for its diagonal removal, and also by possibly more for gcd removals). After we are done with this step, we will later again need the largest. The largest might still be the same number if its count remains >0. However, after we popped it from the heap, it's no longer in the heap. So we would need to push it again. But we could instead not pop until we find a number with positive count and then after processing, we push that number back onto the heap if its count is still >0. Or we could use a different approach: maintain a sorted list of numbers (like a multiset) using something like sortedcontainers, but that's not allowed.
Given n <= 500, n^2 <= 250000, we can actually just maintain a list of all numbers and simulate removals by sorting and using a frequency counter and then each step we need to find the maximum element with positive count. We can precompute the sorted list of distinct values in descending order, and maintain an index pointer to the current maximum. However, after decrementing counts, the maximum may stay the same or move to the next if count becomes zero. Since we only have up to 500 steps, we can simply each time scan the distinct list from the beginning (or from previous max index) to find the first with positive count. The number of distinct values could be up to 250k, and scanning from start each step could be up to 250k * 500 = 125M, which in Python may be okay if optimized? 125M simple integer comparisons might be borderline but perhaps acceptable (1-2 seconds?). However, we can improve: we can maintain a list of distinct numbers sorted descending, and a pointer that moves forward when counts become zero. Since we only decrement counts, once a count becomes zero, that value will never become positive again. So we can maintain an index i that points to the current maximum among positive counts. Initially i=0 (pointing to the largest distinct number). Then while count[distinct[i]] == 0, increment i. Then the maximum is distinct[i]. After processing, we decrement counts of some numbers; these numbers could be equal to the current max or smaller. If the current max's count becomes zero, we increment i until we find a positive count. If the current max's count remains >0, we keep i unchanged (since it's still the max). That works because we never increase counts, only decrease. So we can find the next max in O(1) amortized time: the pointer only moves forward across distinct values. The total number of steps moving the pointer is at most the number of distinct values, which is up to 250k. So that's efficient.
Implementation steps:
-
Read n.
-
Read the list of n^2 numbers.
-
Compute frequency count using a dictionary (Counter).
-
Create a list vals of distinct numbers (keys) and sort descending.
-
Initialize an empty list ans.
-
Initialize pointer idx = 0 to track current max.
-
Loop while len(ans) < n:
- While idx < len(vals) and freq[vals[idx]] == 0: idx += 1.
- Let x = vals[idx].
- Add x to ans.
- Decrement freq[x] by 1 (for diagonal).
- For each y in ans (including the newly added x? Actually we need to process the interactions with previously added elements only. When processing the current x, ans already contains previous elements, and we are about to add x. But careful: The removal should account for the interactions between x and each previously added element. So we should iterate over ans[:-1] (i.e., all elements before adding x). But in the loop, we add x to ans first, then iterate over previous elements? In the examples we did earlier, we removed for each y in ans before adding x? Let's re-evaluate: At the moment we pick x, ans contains previous elements. We need to remove:
- one occurrence of x (diagonal)
- for each y in ans (previous ones), two occurrences of gcd(x, y)
After that, we add x to ans. In the examples, we did: remove one x, then for each y in ans (which didn't include x yet) remove two gcd(x,y), then add x to ans. That's correct.
But in our code, we could first add x to ans, then process removals for all other elements? But careful about the order: If we add x first, then the loop over ans will include x and we would also remove gcd(x, x) which is x two times? That would be wrong because the diagonal for x has already been removed by the one we removed; the interactions between x and itself are only the diagonal, not double. The interaction between x and another copy of x (if there is one) is handled when the second copy is added, by considering y as the previous copy. So when adding the first x, ans previously empty, we just remove one x. If we add x to ans then iterate over ans (which would only contain x), and we remove two gcd(x, x) = x, that would remove two extra x's, which is incorrect. So we should not include the newly added element in the loop. Therefore, we should:
- Decrement freq[x] by 1.
- For each y in ans (the list before adding x): let g = gcd(x, y); decrement freq[g] by 2.
- Then append x to ans.
Or equivalently, we can store ans in a separate list and after removals append. Since we are in a loop, we can do:
cur_ans = ans[:] (but we can just iterate over ans as it is before appending)
So:
for y in ans:
g = gcd(x, y)
freq[g] -= 2
ans.append(x)
But is this algorithm always correct? Let's test on more cases, including when there are duplicate elements and when the maximum appears multiple times.
We tested with [4,3,6,2] from sample. Let's run through:
Given sample input:
4
2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
We need to verify algorithm yields 4 3 6 2 (maybe in different order). Let's compute frequencies: We'll compute later.
But first confirm that the algorithm is widely known for GCD Table problem (CF 582A). Indeed, editorial for 582A "GCD Table" describes exactly this approach: take the largest number from the multiset, add to answer, and for each y in answer, remove two gcd(x,y). This works.
Thus we can implement.
Now corner cases: n=1. Then input has one number, which is the array element. Our algorithm: freq[val] = 1. vals sorted descending: [val]. ans initially empty. idx=0, x=val. Decrement freq[x] by 1 -> becomes 0. Then for each y in ans (none). Append x. Then while len(ans)<1? Already appended, loop ends. Output [val]. Works.
Now about handling the removal of gcd(x,y) by 2: Must ensure that we don't subtract more than available. The problem guarantees that input corresponds to some array, so it will be consistent.
Implementation details:
-
Since n <= 500, number of elements in ans grows up to 500. Each step we compute gcd with all previous ans elements. That's O(n^2) gcd computations, which is fine (max 250k). gcd of numbers up to 1e9 is fast.
-
Data structures: Use collections.Counter for freq.
-
Build list vals = sorted list of keys in descending order.
-
Maintain pointer idx.
Pseudo:
def solve():
import sys, math
input_data = sys.stdin.read().split()
it = iter(input_data)
n = int(next(it))
total = n*n
arr = [int(next(it)) for _ in range(total)]
from collections import Counter
cnt = Counter(arr)
vals = sorted(cnt.keys(), reverse=True)
ans = []
idx = 0
while len(ans) < n:
# find next max with positive count
while idx < len(vals) and cnt[vals[idx]] == 0:
idx += 1
x = vals[idx]
# remove one for diagonal
cnt[x] -= 1
# remove two for each pair with existing ans
for y in ans:
g = math.gcd(x, y)
cnt[g] -= 2
ans.append(x)
# no need to update idx now; we'll check at start of next iteration
# output ans (space-separated)
print(' '.join(map(str, ans)))
But wait: In the loop, after removing the diagonal and the gcds, the count of x might become zero. That's fine. Next iteration, the while loop will skip zero counts. However, we also might have decreased count of some numbers that are larger than x? None because x is the maximum among positive counts. However, there is a subtlety: When we decrement freq of gcd(x,y), it's possible that g equals x (if y is a multiple of x or vice versa). For example, if x=6 and y=12, gcd=6. Then we subtract 2 from cnt[6]. That's fine; we might reduce cnt[6] further. Since x is the current max, and if we subtract 2 from cnt[x], it could become negative if not enough counts. But because the input is consistent, it will be exactly the right number.
Now, what about the case where x is not the maximum? In our algorithm we always pick the maximum. But after we remove contributions for x with previous elements, it's possible that the new maximum (the next iteration) is still x if its count remains >0 (due to duplicates). That's okay because idx still points to x and its count is positive, so we will pick it again. However, if its count becomes zero, idx will move forward.
Now, about the pointer: We need to ensure that after we decrement counts, we don't inadvertently skip some values that become zero and are before idx? Since idx points to the current max (which is the largest value with positive count). After processing, if we decrement count of x and it becomes zero, then the next max will be the next value with positive count. But what if there is a value larger than x? There can't be because x was the maximum among positive counts before processing. So all values > x have count zero already. So the next max is either still x (if count >0) or the next smaller value with positive count. So moving idx forward as we skip zeros will work. However, after we decrement counts of some numbers smaller than x, we might cause them to become zero, but they are after idx. That doesn't affect the next max search because we only care about the largest positive count, which will be at idx or later. Since we only move idx forward, we might skip over values that we haven't yet considered but are zero now. That's fine.
But we must be careful: The pointer idx starts at 0 (largest value). After we process x (the largest), we may need to consider that the same x might still be max if its count >0. However, our while loop at the start of next iteration will check cnt[vals[idx]] == 0. If we left idx pointing to x and its count became 0, then we will increment idx until we find a positive count, which will be the next max. If count is still positive, we stay at idx, and x will be selected again. So correct.
Now, one more nuance: When we have duplicate values, the algorithm as described will pick the same value multiple times, as needed. Example with three 6s: after first 6, we removed one 6 and no gcd with previous (since none). Count of 6 originally 9, after removal becomes 8. Then ans = [6]. Next iteration, max is 6 (count 8 >0). We process second 6: remove one 6 -> count 7; then for y in ans (only 6) -> gcd(6,6)=6, remove two 6 -> count 5. Append 6. Next iteration, max still 6 (count 5 >0). Process third 6: remove one 6 -> count 4; for y in ans (two elements: 6 and 6) -> remove two 6 for each -> remove 4 -> count 0. Works.
Now, test with the sample input:
Input:
4
2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
We need to compute frequencies. Let's list all numbers:
Given: 2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
We can count:
Let's sort to count: Actually let's compute manually:
Numbers: 2,1,2,3,4,3,2,6,1,1,2,2,1,2,3,2.
We can list each:
- 2
- 1
- 2
- 3
- 4
- 3
- 2
- 6
- 1
- 1
- 2
- 2
- 1
- 2
- 3
- 2
So frequencies:
1: appears at positions 2,9,10,13 => 4 times? Let's count: 2,9,10,13 -> that's 4. (Also check if any other 1: position 2,9,10,13 -> yes 4)
2: positions 1,3,7,11,12,14,16? Also position? Let's count: 1,3,7,11,12,14,16 -> that's 7? Also maybe position? Wait there are many 2's. Let's count systematically: The numbers: [2,1,2,3,4,3,2,6,1,1,2,2,1,2,3,2]. So let's index:
0:2
1:1
2:2
3:3
4:4
5:3
6:2
7:6
8:1
9:1
10:2
11:2
12:1
13:2
14:3
15:2
Count 2: indices 0,2,6,10,11,13,15 -> that's 7. Also maybe index? That's 7.
3: indices 3,5,14 -> 3.
4: index 4 -> 1.
6: index 7 -> 1.
Check total: 4+7+3+1+1 = 16. OK.
So frequencies: 1:4, 2:7, 3:3, 4:1, 6:1.
Now run algorithm:
vals sorted descending: [6,4,3,2,1]
cnt = {6:1,4:1,3:3,2:7,1:4}
ans=[]
Step1: idx=0, x=6 (cnt 1>0). Remove one 6 -> cnt[6]=0. No previous ans, so nothing else. ans=[6].
Now after step, cnt: 6:0,4:1,3:3,2:7,1:4. Next iteration: while cnt[vals[idx]]==0? idx=0 -> vals[0]=6 cnt=0 -> idx=1. vals[1]=4 cnt=1>0 -> x=4. Remove one 4 -> cnt[4]=0. For each y in ans (6): g=gcd(4,6)=2, cnt[2] -=2 -> cnt[2]=7-2=5. ans becomes [6,4].
Now cnt: 6:0,4:0,3:3,2:5,1:4. Next iteration: idx=1? At start of loop, while cnt[vals[idx]]==0? idx=1, vals[1]=4 cnt=0 -> idx=2. vals[2]=3 cnt=3>0 -> x=3. Remove one 3 -> cnt[3]=2. For each y in ans: y=6 -> g=gcd(3,6)=3 -> cnt[3] -=2 -> cnt[3]=2-2=0. y=4 -> g=gcd(3,4)=1 -> cnt[1] -=2 -> cnt[1]=4-2=2. ans becomes [6,4,3].
Now cnt: 6:0,4:0,3:0,2:5,1:2. Next iteration: while cnt[vals[idx]]==0? idx=2 -> vals[2]=3 cnt=0 -> idx=3. vals[3]=2 cnt=5>0 -> x=2. Remove one 2 -> cnt[2]=4. For each y in ans (6,4,3):
y=6: g=gcd(2,6)=2 -> cnt[2] -=2 -> cnt[2]=4-2=2
y=4: g=gcd(2,4)=2 -> cnt[2] -=2 -> cnt[2]=2-2=0