The peak that looks highest
Time limit5sMemory limit512 MB
Given each peak's apparent-highest peak ahead, assign integer heights matching all sightings and print the lexicographically smallest heights or Impossible.
- Level
Hard8 of 10
- Topics
- Geometry, Backtracking, Math
- Solved
- No attempts yet
Problem
You are hiking along a mountain range. There is exactly one peak every kilometer and nothing in between, so the peaks are numbered through in the order you walk them. On every peak you lie down to rest, look ahead, and one of the peaks in front of you looks like the highest one.
The peak that looks highest is not always the highest one. A taller peak can hide behind a nearer and lower peak, and when you look downhill a faraway peak can look higher than a close one.
Peak looks highest from peak when all three of these hold: is further down the road than , every peak between and is strictly below the line through the tops of and , and every peak beyond is on or below that line.

In the picture, peak looks highest from peak and from peak . From peak you cannot see peak at all, because peak hides it, so peak looks highest.
You do not know how high the peaks are, but you remember which peak looked highest from each of them. Assign heights that agree with that memory. You were lying down, so treat every sighting as taken from the ground level of the peak you were on.
Input
The first line has the number of test cases . Each test case takes two lines. The first line has , the number of peaks. Your walk starts on peak and ends on peak . The second line has numbers , where is the index of the peak that looked highest from peak . Peak is the last one, so it records nothing.
Output
For each test case print one line in the form Case #n: y1 y2 ... yN, where n is the test case number starting from 1 and is the height of peak . Every height must be an integer between and , inclusive.
Several assignments of heights can agree with the same memory, so print the lexicographically smallest one. A sequence is lexicographically smaller than a sequence when holds the smaller value at the first position where the two differ.
If no assignment of heights agrees with the memory, print Case #n: Impossible instead.