/
| 29 | |
| 30 | /*********************************************************/ |
| 31 | int complete_seq(int *B, int Max, int N, int initial_direction) |
| 32 | /* Given B[0],..., B[N-1] as in the ELEVATR problem, |
| 33 | complete the sequence, using the minimal number |
| 34 | of direction changes. |
| 35 | Return value: |
| 36 | -1 : the sequence is invalid, and cannot be completed; e.g., 1 -1 4 |
| 37 | n>=0: the minimal number of direction changes required. |
| 38 | Upon completion, 'B' will have been altered to contain a sequence |
| 39 | achieving the minimum. |
| 40 | */ |
| 41 | { int d, d_changes, j; |
| 42 | int psteps, nsteps, steps; |
| 43 | int current_floor, next_floor; |
| 44 | int current_index, next_index; |
| 45 | |
| 46 | d_changes = 0; |
| 47 | current_index = 0; |
| 48 | d = initial_direction; |
| 49 | |
| 50 | current_floor = B[current_index]; |
| 51 | if (current_floor == -1) { |
| 52 | /* Special case: unknown starting location. */ |
| 53 | next_index = get_next_index(B, current_index, N); |
| 54 | next_floor = B[next_index]; |
| 55 | if (next_floor == -1) { |
| 56 | if (d>0) |
| 57 | B[next_index] = Max; |
| 58 | else |
| 59 | B[next_index] = 1; |
| 60 | } |
| 61 | |
| 62 | /* Fill in everything up to 'next_floor'. It's simplest to work backwards: */ |
| 63 | d = initial_direction; |
| 64 | for (j=next_index-1; j>=0; j--) { |
| 65 | if ( ((B[j+1]-d)<1) || (B[j+1]-d > Max)) { |
| 66 | d *= -1; |
| 67 | d_changes += 1; |
| 68 | } |
| 69 | B[j] = B[j+1]-d; |
| 70 | } |
| 71 | current_index = next_index; |
| 72 | } |
| 73 | |
| 74 | d = initial_direction; |
| 75 | while (current_index < N-1) { |
| 76 | current_floor = B[current_index]; |
| 77 | next_index = get_next_index(B, current_index, N); |
| 78 | next_floor = B[next_index]; |
| 79 | |
| 80 | steps = next_index - current_index; |
| 81 | if (next_floor > 0) { |
| 82 | /* Determine the required numbers of positive steps and negative steps as follows: */ |
| 83 | /* next_floor - current_floor = psteps - nsteps, |
| 84 | steps = psteps + nsteps. |
| 85 | ==> 2*psteps = next_floor - current_floor + steps. |
| 86 | */ |
| 87 | psteps = next_floor - current_floor + steps; |
| 88 | if (psteps % 2) return -1; |
no test coverage detected