#P15897. [TOPC 2025] Explosive Slabstones Rearrangement

[TOPC 2025] Explosive Slabstones Rearrangement

Description

Barbara has a garden. The garden can be represented as a n×mn \times m grid. She has placed kk slabstones in the garden, so she can enjoy stepping slabstones from one to another every day. The slabstones are indexed from 11 to kk. Each slabstone fully occupies some cell of the garden, and no two slabstones are placed at the same cell.

However, an evil person, Babara, is going to place a special device that will occupy a rectangular region in the garden. If any slabstone overlaps with the device, it will explode and destroy the whole garden!

To avoid the explosion, Barbara wants to rearrange the slabstones by shifting the slabstones within the garden. The slabstones should remain non-overlapping during slabstone rearrangement. The energy spent is equal to the largest index among all slabstones that have been moved. Now Barbara wants to know the minimum energy required to rearrange the slabstones, so she can save her energy for “other purposes”.

For example, suppose the device will be placed at the blue rectangle. Then Barbara can rearrange the slabstones as follows. Please note that the slabstones do not overlap during the whole process, not only after the rearrangement. All slabstones that have been moved have index at most 44, so the energy spent is 44.

:::align{center} :::

Input Format

The first line contains three integers nn, mm and kk.

Followed by kk lines, the ii-th of which contains two integers xix_i and yiy_i, representing that the ii-th slabstone is located at the yiy_i-th cell of the xix_i-th row.

The last line contains four integers u1u_1, v1v_1, u2u_2 and v2v_2, representing that the top-left corner of the device is located at the v1v_1-th cell of the u1u_1-th row, and the bottom-right corner of the device is located at the v2v_2-th cell of the u2u_2-th row.

Output Format

Print the minimum energy required to rearrange the slabstones. If no slabstones need to be moved, the energy spent is 00. If the explosion cannot be avoided, just output 1-1.

3 5 8
1 4
1 5
2 3
2 2
3 3
3 4
2 5
1 2
1 3 1 5
4
3 3 1
2 2
1 1 3 3
-1

Hint

  • 1n5001 \le n \le 500
  • 1m5001 \le m \le 500
  • 1kn×m1 \le k \le n \times m
  • 1xin1 \le x_i \le n
  • 1yim1 \le y_i \le m
  • 1u1u2n1 \le u_1 \le u_2 \le n
  • 1v1v2m1 \le v_1 \le v_2 \le m
  • All (xi,yi)(x_i, y_i) pairs are distinct.