Ancient Lock

Interview

Time limit1sMemory limit128 MB

Summary
Group locks by whether one lock's row sequence is a constant horizontal shift of another, and count the number of distinct groups (keys) needed.
Level

Easy3 of 10

Topics
Array, Hash map, Implementation
Solved
No attempts yet

Problem

An old document chest is fitted with intricate locks. Each lock is a rectangle WW cm wide and LL cm tall, and consists of an upper part, a lower part, and the empty space between them.

Each lock is described by two sequences of LL non-negative integers. In row ii, the upper part extends aia_i cm inward from the left edge and the lower part extends bib_i cm inward from the right edge, leaving W−ai−biW - a_i - b_i cm of empty space between them.

A key that fits a lock is a clay tab that fills this empty space exactly. Because a key is a single rigid piece, it can only be slid in with a horizontal shift. Hence two locks are opened by the same key if and only if one is a horizontal translation of the other: there exists an integer dd such that ai′=ai+da'_i = a_i + d and bi′=bi−db'_i = b_i - d for every ii.

The figure below shows an example lock of width 8 cm and height 7 cm together with a matching key. Its upper sequence is {2,1,3,2,3,2,3}\{2, 1, 3, 2, 3, 2, 3\} and its lower sequence is {3,4,2,3,2,3,4}\{3, 4, 2, 3, 2, 3, 4\}.

A single key may open two or more locks. To minimize the number of keys you must craft, determine the minimum number of keys needed to open all of the given locks.

Input

The first line contains the lock width WW (1≤W≤1081 \le W \le 10^8), the height LL (1≤L≤10001 \le L \le 1000), and the number of locks NN (1≤N≤1001 \le N \le 100), separated by spaces.

The next 2N2N lines describe the locks. Each lock is given on two lines: the first line is the upper sequence a1,a2,…,aLa_1, a_2, \dots, a_L and the second line is the lower sequence b1,b2,…,bLb_1, b_2, \dots, b_L. Every value is at least 00 and less than WW, and in every row there is at least 1 cm of empty space between the upper and lower parts (that is, ai+bi<Wa_i + b_i < W for all ii).

Output

Print, on a single line, the minimum number of keys needed to open all of the locks.

Examples3

  1. Example 1

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

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

    Input
    100000000 2 2
    88888888 88888888
    4 4
    4 4
    88888888 88888888
    
    Expected output
    1