This page is still under construction.

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

Jengaism

Time limit1sMemory limit128 MB

Summary
Simulate Jenga moves (remove a block, place it on top) and report when any structure topples because its center of gravity leaves the convex hull of its supports.
Level

Hard8 of 10

Topics
Geometry, Simulation, Implementation, Greedy
Solved
No attempts yet

Problem

Jenga is a popular game in which a tower is built from 1×1×31 \times 1 \times 3 blocks. Initially the tower has 1818 levels, each made of three blocks laid side by side. Blocks on adjacent levels are oriented at right angles to one another, so every block touches all three of the blocks in the level directly above it and directly below it. A picture of the real game is shown below.

On each turn a player removes one block from somewhere in the tower and places it on top. The goal is to keep doing this without knocking the tower over. A block is always removed from below the highest completed level, and the top level is always completed (at right angles, of course) before a new level is started.

Write a program that reads the moves of a Jenga game in order and determines the moment at which the tower — or any part of it — falls or topples.

A structure topples if the vertical projection of its center of gravity onto its base lies outside the convex hull of its support points. If the center of gravity lies exactly on the edge of that hull, the structure is considered stable.

Input

The first line contains NN, the number of moves. Each of the next NN lines describes one move as two locations separated by a single space: the first is the location of the block to be removed, and the second is where it will be placed. A location is written as a number giving the level, followed by a letter A–C giving the position within that level (left to right, or front to back). For example, in the initial tower the top level consists of the blocks 18A, 18B, and 18C. The diagrams below label the pieces as seen from the front and from the right side.

18C
17A17B17C
16C
15A15B15C
14C
13A13B13C
12C
11A11B11C
10C
9A9B9C
8C
7A7B7C
6C
5A5B5C
4C
3A3B3C
2C
1A1B1C
18A18B18C
17C
16A16B16C
15C
14A14B14C
13C
12A12B12C
11C
10A10B10C
9C
8A8B8C
7C
6A6B6C
5C
4A4B4C
3C
2A2B2C
1C

Output

If the tower collapses after removing a block at location LL, print The tower collapses after removing L.

If the tower collapses after placing a block at location LL, print The tower collapses after placing L.

If every move executes successfully without the tower falling, print The tower never collapses.

Examples2

  1. Example 1

    Input
    4
    6B 19B
    7B 19A
    17B 19C
    17A 20B
    
    Expected output
    The tower collapses after removing 17A
    
  2. Example 2

    Input
    2
    17C 19C
    17A 19A
    
    Expected output
    The tower never collapses