Ancient Lock
InterviewTime limit1sMemory limit128 MB
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 cm wide and 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 non-negative integers. In row , the upper part extends cm inward from the left edge and the lower part extends cm inward from the right edge, leaving 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 such that and for every .
The figure below shows an example lock of width 8 cm and height 7 cm together with a matching key. Its upper sequence is and its lower sequence is .

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 (), the height (), and the number of locks (), separated by spaces.
The next lines describe the locks. Each lock is given on two lines: the first line is the upper sequence and the second line is the lower sequence . Every value is at least and less than , and in every row there is at least 1 cm of empty space between the upper and lower parts (that is, for all ).
Output
Print, on a single line, the minimum number of keys needed to open all of the locks.