Queen Collisions
Time limit1sMemory limit128 MB
Given groups of queens placed along arithmetic progressions on an n by n board, count pairs that share a row, column, or diagonal with no queen between them.
- Level
Medium7 of 10
- Topics
- Math, Sorting, Hash map, Implementation
- Solved
- No attempts yet
Problem
Several queens are placed on a chessboard. Two distinct queens collide if they lie on the same row, the same column, or the same diagonal, and there is no other queen between them along that line. The board size and the number of queens vary from case to case.
On an board, each queen's position is written as coordinates , where is a column number from to and is a row number from to . Two distinct positions and are related as follows:
- If , they lie on the same row.
- If , they lie on the same column.
- If , they lie on the same diagonal.
In each of these cases the two queens collide only if no other queen lies directly between them along that line (row, column, or diagonal). Hence, when several queens lie on one line, only the neighboring queens along that line collide. For example, if the five queens lie on one anti-diagonal, the collisions occur only between the four pairs –, –, –, and –.
Queens are often placed in regular patterns. Such regularity lets the positions of many queens be stated compactly, so the input is given as groups of queens placed in arithmetic progression (linear patterns). Write a program that counts the total number of collisions in the given arrangement.
Input
The input consists of one to twenty data sets, followed by a line containing only .
The first line of each data set contains two blank-separated positive integers and . Here means the board size is with , and is the number of linear patterns described next with . Each of the next lines contains five blank-separated integers , representing queens placed at positions for . The value is a positive integer. If , the values of and are irrelevant and are given as .
Every queen position lies on the board. The total number of queen positions across all linear patterns in one data set does not exceed , and all of these positions are distinct.
Output
For each data set, print on one line the total number of collisions in that arrangement.
The number of queens can be large, so take care that your algorithm is efficient.