Factor-Free Tree
Time limit6sMemory limit512 MB
Given a sequence, decide whether it can be the inorder of a rooted binary tree where every node is coprime with all its ancestors, and if so output each node's parent index.
- Level
Hard8 of 10
- Topics
- Tree, Divide and conquer, Number theory, Implementation
- Solved
- No attempts yet
Problem
A factor-free tree is a rooted binary tree in which every node holds one positive integer, and the value of every node is coprime with the values of all of its ancestors. Two positive integers are coprime when their greatest common divisor is 1.
The inorder sequence of a rooted binary tree is built recursively: first the left subtree, then the root, then the right subtree.

The tree above is factor-free. For example, the value 5 is coprime with the values 9, 8 and 7 written in the ancestors of that node.
You are given a sequence . Decide whether some factor-free tree has this sequence as its inorder sequence, and build such a tree if one exists.
Input
The first line contains the length of the sequence ().
The second line contains the integers of the sequence, separated by spaces ().
Output
If a factor-free tree has the given sequence as its inorder sequence, print numbers on one line, separated by spaces. The -th number is the 1-based index of the parent of the -th element, or 0 if the -th element is the root.
Several trees can satisfy the condition, so only the tree built by the following rule counts as correct. Build the tree of a block of consecutive positions like this. Take as its root the smallest position in the block whose value is coprime with every other value of the block, then build the left subtree by applying the same rule to the block and the right subtree by applying it to the block . The whole sequence is the block . If some block has no such position, no factor-free tree has the given sequence as its inorder sequence.
If no such tree exists, print impossible instead.