#P16978. [NWERC 2017] Factor-Free Tree

[NWERC 2017] Factor-Free Tree

Background

From Northwestern Europe Regional Contest (NWERC) 2017 Problem F.

Original problem license: CC BY-SA.

Problem Description

A factor-free tree is a rooted binary tree where every node in the tree contains a positive integer value that is coprime with all of the values of its ancestors. Two positive integers are coprime if their greatest common divisor equals 11.

The inorder sequence of a rooted binary tree can be generated recursively by traversing first the left subtree, then the root, then the right subtree. See Figure 1 below for the inorder sequence of one factor-free tree.

:::align{center} :::

Figure 1: Illustration of Sample 1. The tree is factor-free; for example, the value of the node marked "55" is coprime with all of the values of its ancestors, marked "99", "88", and "77".

Given a sequence a1,a2,,ana_1,a_2,\ldots,a_n, decide if it is the inorder sequence of some factor-free tree and if so construct such a tree.

Input Format

The input consists of:

  • One line with one integer nn (1n1061 \leq n \leq 10^6), the length of the sequence.
  • One line with nn integers a1,,ana_1,\ldots,a_n (1ai1071 \leq a_i \leq 10^7 for each ii), the elements of the sequence.

Output Format

If there exists a factor-free tree whose inorder sequence is the given sequence, output nn values. For each value in the sequence, give the 11-based index of its parent, or 00 if it is the root. If there are multiple valid answers, print any one of them. If no such tree exists, output impossible instead.

6
2 7 15 8 9 5
2 0 4 2 4 5
6
2 7 15 8 9 6
impossible