Queen Collisions#1813

Queen Collisions

1 second
64 megabytes
Very easy

A lot of time has been spent by computer science students dealing with queens on a chessboard. Two queens on a chessboard collide if they are on the same row, column, or diagonal, and there is no piece between them. Boards of various sizes and numbers of queens are considered. For example, in Figure , a 7 \times 7 board contains queens with no collisions. In Figure , there is a 5 \times 5 board with queens and collisions. In Figure , a traditional 8 \times 8 board, there are queens and collisions.

On an n \times n board, queen positions are given in Cartesian coordinates , where is the column number from to , and is the row number from to . Queens at distinct positions (x_1, y_1) and (x_2, y_2) are on the same diagonal if |x_1-x_2| = |y_1-y_2|. They are on the same row or column if y_1 = y_2 or x_1 = x_2, respectively. In each of these cases, the queens have a collision if there is no other queen directly between them on the same diagonal, row, or column. For example, in Figure , the collisions are between the queens at and , and , and , and finally and . In Figure , the collisions are between the queens at and , and , and , and , and finally and . Your task is to count the number of queen collisions.

In many situations there are a number of queens placed in a regular pattern. For instance, in Figure there are queens in a line at , , , and . Each of these queens, after the first at , is one to the right and up from the previous one. Three queens starting at follow a similar pattern. Noting these patterns allows the positions of a large number of queens to be described concisely.

Input

The input consists of one to twenty data sets, followed by a line containing only .

The first line of a data set contains space-separated positive integers , where indicates the size of the n \times n board and is the number of linear patterns of queens to be described, where n < 30000 and g < 250. The next lines each contain five space-separated integers , representing a linear pattern of queens at locations (x + i \cdot s, y + i \cdot t), for i = 0, 1, \ldots, k-1. The value of is positive. If k = 1, then the values of and are irrelevant and will be given as . All queen positions will be on the board. The total number of queen positions among all the patterns will be at most , and all positions will be distinct.

Output

For each data set, output one line containing only the number of collisions between the queens.

The sample input dataset corresponds to the configuration in the figures.

Take care with your algorithm, or your solution may take too long.

Examples

Example

Input

7 2
4 1 1 1 2
3 5 2 1 2
5 1
5 1 1 1 1
8 4
1 1 8 0 0
2 4 8 0 -1
2 6 5 1 1
2 2 1 1 1
0
Output

0
4
5

Example 1

Loading
Loading