eolymp
bolt
Try our new interface for solving problems
Problems

Permutations

Permutations

Given set of \textbf{n} different positive integers. Permutation of the elements of this set is called a\textbf{k}\textit{-}permutation, if for any two adjacent elements of the permutation of their greatest common factor of not less than \textbf{k}. For example, if a given set of elements \textbf{S} = \{\textbf{6}, \textbf{3}, \textbf{9}, \textbf{8}\}, the permutation of \{\textbf{8}, \textbf{6}, \textbf{3}, \textbf{9}\} is a \textbf{2}-permutation, a permutation of \{\textbf{6}, \textbf{8}, \textbf{3}, \textbf{9}\} -- no. Rearrange \{\textbf{p_1}, \textbf{p_2}, …, \textbf{p_n}\} is lexicographically smaller permutation of \{\textbf{q_1}, \textbf{q_2}, …, \textbf{q_n}\}, if there exists an integer \textbf{i} (\textbf{1} ≤ \textbf{i} ≤ \textbf{n}), for which \textbf{p_j}\textit{ = }\textbf{q_j} for \textbf{j}\textit{ < }\textbf{i} and \textbf{p_i}\textit{ < }\textbf{q_i}. As an example, order all the \textbf{k}-permutation of a given above sets in lexicographical order. For example, there are exactly four \textbf{2}-permutation of the set \textbf{S}: \{\textbf{3}, \textbf{9}, \textbf{6}, \textbf{8}\}, \{\textbf{8}, \textbf{6}, \textbf{3}, \textbf{9}\}, \{\textbf{8}, \textbf{6}, \textbf{9}, \textbf{3}\} and \{\textbf{9}, \textbf{3}, \textbf{6}, \textbf{8}\}. Accordingly, the first \textbf{2}-permutation in lexicographical order is the set \{\textbf{3}, \textbf{9}, \textbf{6}, \textbf{8}\}, and the fourth - the set\textbf{ }\{\textbf{9}, \textbf{3}, \textbf{6}, \textbf{8}\}. Need to write a program that allows to find the \textbf{m}-th \textbf{k}-permutation in that order. \InputFile The first line contains three natural numbers \textbf{n} (\textbf{1}\textit{ }≤\textit{ }\textbf{n}\textit{ }≤\textit{ }\textbf{16}), \textbf{m}\textit{ }and \textbf{k}\textit{ (}\textbf{1}\textit{ ≤ }\textbf{m}\textit{, }\textbf{k}\textit{ ≤ }\textbf{10^9}\textit{)}. The second line contains \textbf{n} distinct positive integers not exceeding \textbf{10^9}. All numbers in rows are separated by a space. \OutputFile Print \textbf{m}-th \textbf{k}-permutation of a given set, or \textbf{-1} if no such.
Time limit 2 seconds
Memory limit 64 MiB
Input example #1
1 1 1
1
Output example #1
1
Source 2009 Областная олимпиада школьников по информатике, Вологда, Задача H