Under construction

Still being built. Things may change

Cultivation

Time limit2sMemory limit512 MB

Summary
Given N grass cells on a huge R by C grid, find the fewest years needed to fill every cell when each year's wind blows in one of four directions.
Level

Hard8 of 10

Topics
Binary search, Greedy, Sorting
Solved
No attempts yet

Problem

In 21XX, the residents of the IOI planet plan to immigrate to a recently discovered planet.

The new planet has a field, a rectangular grid with R rows and C columns. The columns run along the south-north direction, and the rows run along the east-west direction. The cell in the i-th row from the north and the j-th column from the west is cell (i, j). The northwest corner of the field is cell (1, 1), and the southeast corner is cell (R, C). Each year, the residents choose the direction of the wind blowing over the field: east, west, south, or north.

To farm the new planet, they will plant JOI grasses over the entire field. In the spring of the first year, N cells of the field have JOI grasses.

JOI grasses spread with the wind. Each summer, the seeds are blown in the direction the residents chose. Each seed moves one cell in that direction and lands there. If a seed lands on a cell without JOI grasses, that cell has JOI grasses in the spring of the next year. Once a cell has JOI grasses, it keeps them.

Adjusting the wind direction appropriately, find the minimum number of years until every cell of the field has JOI grasses. Write a program that computes this.

Input

The first line contains two space-separated integers R and C. The field is an R by C grid.

The second line contains an integer N, the number of cells that have JOI grasses in the spring of the first year.

Each of the following N lines contains two space-separated integers Si and Ei. This means cell (Si, Ei) has JOI grasses in the spring of the first year.

Output

Print one line containing the minimum number of years until every cell of the field has JOI grasses, when the wind direction is adjusted appropriately.

Constraints

  • 1 ≤ N ≤ 300.
  • 1 ≤ R ≤ 1 000 000 000.
  • 1 ≤ C ≤ 1 000 000 000.
  • 1 ≤ Si ≤ R (1 ≤ i ≤ N).
  • 1 ≤ Ei ≤ C (1 ≤ i ≤ N).
  • In the spring of the first year, at least one cell does not have JOI grasses.
  • (Si, Ei) ≠ (Sj, Ej) (1 ≤ i < j ≤ N).

Examples2

  1. Example 1

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

    Input
    4 4
    4
    1 1
    1 4
    4 1
    4 4
    
    Expected output
    4