This page is still under construction.

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

The Mansion

Time limit1sMemory limit256 MB

Summary
In a grid where only vertical doors start open, find the shortest time to go from (1,1) to (M,N), where holding a switch in certain rooms for a minute flips every door's state.
Level

Medium7 of 10

Topics
Graph, BFS, Shortest path, Greedy
Solved
No attempts yet

Problem

You are trapped in a huge mansion. The mansion is a grid of square rooms with NN rows and MM columns. The room that is the xx-th from the left (1≤x≤M1 \le x \le M) and the yy-th from the bottom (1≤y≤N1 \le y \le N) is denoted (x,y)(x, y).

Between every pair of adjacent rooms there is exactly one door, and each door is either open or closed. Passing through an open door into a neighboring room takes 11 minute. You may only move through open doors, and you cannot change a door's state directly.

Some rooms have a switch at their center. Holding a switch down for 11 minute flips the state of every door in the mansion: every open door becomes closed and every closed door becomes open.

Initially, only the doors between vertically adjacent rooms (one directly above the other) are open; all other doors are closed.

You are currently at the center of room (1,1)(1, 1) and want to reach the center of room (M,N)(M, N). Find the minimum time needed to get there.

Input

The first line contains the mansion size MM, NN and the number of rooms that have a switch, KK, separated by spaces. Each of the next KK lines contains the position xix_i, yiy_i of a room that has a switch. (2≤M,N≤1000002 \le M, N \le 100000, 1≤K≤2000001 \le K \le 200000)

Output

Print the minimum time to reach room (M,N)(M, N) on the first line. If (M,N)(M, N) cannot be reached, print −1-1.

Examples3

  1. Example 1

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

    Input
    3 2 1
    2 1
    
    Expected output
    -1
    
  3. Example 3

    Input
    8 9 15
    3 1
    3 2
    3 7
    3 8
    1 1
    4 5
    4 3
    5 6
    5 8
    6 3
    6 2
    7 5
    8 9
    8 6
    8 5
    
    Expected output
    25