This page is still under construction.

Parts of this page are still being built. What you see may change.

Gondola sequence check

Time limit1sMemory limit256 MB

Summary
Decide whether n observed gondola numbers could appear as consecutive passings on a circle where broken gondolas are replaced in order by numbered spares.
Level

Medium5 of 10

Topics
Simulation, Hash map, Linked list
Solved
No attempts yet

Problem

The Maokong gondola in Taipei runs on a circular track with one station. Initially gondolas 11 through nn sit in order, all moving the same way. After gondola ii passes the station, gondola i+1i+1 passes next (after nn comes 11).

Gondolas can break. Spare units are numbered n+1,n+2,…n+1, n+2, \ldots and the smallest unused spare replaces a broken gondola in the same slot. With n=5n=5, if gondola 11 breaks it becomes gondola 66.

Write down the numbers of nn consecutive passings at the station in order to form a gondola sequence. Some breaks may already have happened before you start writing, but no gondola breaks while you write.

The same physical layout can yield different sequences depending on when you start. With no breaks, (2,3,4,5,1)(2,3,4,5,1) and (4,5,1,2,3)(4,5,1,2,3) are valid but (4,3,2,5,1)(4,3,2,5,1) is not.

If only gondola 11 broke, (4,5,6,2,3)(4,5,6,2,3) is possible. If gondola 44 then breaks and becomes 77, (6,2,3,7,5)(6,2,3,7,5) works. If 77 later breaks and becomes 88, (3,8,5,6,2)(3,8,5,6,2) is also possible.

Broken gondolaReplacementOne valid sequence
16(4, 5, 6, 2, 3)
47(6, 2, 3, 7, 5)
78(3, 8, 5, 6, 2)

The replacement sequence lists broken gondolas in break order; here it is (1,4,7)(1,4,7).

Decide whether the input sequence could appear after some replacement history.

Input

The first line contains nn.

The second line contains nn integers.

Output

Print 11 if the sequence is possible, otherwise 00.

Hint

Keep the next-gondola map on the circle. For each original id 1..n1..n missing from the sequence, replace it with the next spare id, chaining further replacements when a spare is also absent. Finally verify every consecutive pair in the input follows the successor links.

Examples3

  1. Example 1

    Input
    6
    3 4 5 6 1 2
    
    Expected output
    1
    
  2. Example 2

    Input
    7
    1 2 3 4 5 6 7
    
    Expected output
    1
    
  3. Example 3

    Input
    6
    1 5 3 4 2 7
    
    Expected output
    0