The queue q contains sets of trees that are reachable from each other. Each set is represented by the index of the tallest tree in that set. For each tree, I iterate through and update q. This solution should fail when n is large and a is sorted, since then every set consists of a single tree.