This page is still under construction.

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

Cow Rescue

Time limit1sMemory limit128 MB

Summary
Find the minimum walking time from a start triangle to any exit in a triangular maze with up to a million rows, then break ties by row and column.
Level

Medium7 of 10

Topics
Graph, Shortest path, Math, Geometry
Solved
No attempts yet

Problem

Bessie is trapped in a triangular maze with NN rows (1≤N≤1,000,0001 \le N \le 1{,}000{,}000). Row ii of the maze contains 2i−12i-1 triangles. Numbering from the left, the triangles in row ii are named (i,1),(i,2),…,(i,2i−1)(i,1), (i,2), \dots, (i, 2i-1).

Each triangle shares an edge with (usually three) neighboring triangles, and Bessie can move to any triangle that shares an edge with her current one. For example, from triangle (3,3)(3,3) she can move to (3,2)(3,2), (3,4)(3,4), and (4,4)(4,4). Each move takes exactly 11 minute.

(Triangles in odd columns point upward and those in even columns point downward. An upward triangle (i,j)(i,j) is adjacent to (i,j−1)(i,j-1), (i,j+1)(i,j+1), and (i+1,j+1)(i+1,j+1); a downward triangle (i,j)(i,j) is adjacent to (i,j−1)(i,j-1), (i,j+1)(i,j+1), and (i−1,j−1)(i-1,j-1). Neighbors outside the maze do not exist.)

Bessie starts at triangle (Si,Sj)(S_i, S_j). The maze has MM exit triangles (1≤M≤10,0001 \le M \le 10{,}000). Reaching any exit lets Bessie escape: once she enters an exit triangle, she leaves the maze after one more minute.

Let TT be the minimum number of minutes Bessie needs to escape. Among all exits that let her escape in exactly TT minutes, report the one she should use: choose the exit in the smallest row, and if there is still a tie, the exit with the smallest column.

Input

  • Line 1: two space-separated integers NN and MM.
  • Line 2: two space-separated integers SiS_i and SjS_j — Bessie's starting triangle.
  • Lines 3 through M+2M+2: line i+2i+2 contains two space-separated integers EiE_i and EjE_j, the location of exit ii.

Output

  • Line 1: two space-separated integers OUTiOUT_i and OUTjOUT_j — the chosen exit location.
  • Line 2: a single integer TT — the minimum escape time in minutes.

Examples6

  1. Example 1

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

    Input
    1 1
    1 1
    1 1
    
    Expected output
    1 1
    1
    
  3. Example 3

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

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

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

    Input
    4 2
    4 1
    4 7
    4 4
    
    Expected output
    4 4
    4