Toy Animals
Time limit2sMemory limit128 MB
Count pairs of points on a 1D, 2D, or 3D integer grid whose Manhattan distance is at most D.
- Level
Hard8 of 10
- Topics
- Divide and conquer, Sorting, Geometry, Bit manipulation
- Solved
- No attempts yet
Problem
Sanggeun and Seonyoung are playing with toy animals. First they pick one of the three game boards below. Each board is made up of many cells; board is one-dimensional (a line), board is two-dimensional (a grid), and board is three-dimensional (a solid grid).

Each cell is identified by integer coordinates, and adjacent cells are joined by a line segment.
- Board : a cell is written as , and cell is adjacent to cells and .
- Board : a cell is written as , and cell is adjacent to and .
- Board : a cell is written as , and cell is adjacent to , , and .
Sanggeun places toy animals on the cells. Several animals may share the same cell.
The distance between two cells is the least number of moves needed to travel from one to the other. Because each move goes to an adjacent cell, the distance equals the sum of the absolute differences of the coordinates.
- Board :
- Board :
- Board :
Two toy animals can hear each other when the distance between their cells is at most . Given the board type, the position of every toy animal, and , write a program that counts the number of pairs of toy animals that can hear each other.
Input
The first line contains four integers , , , and separated by spaces.
- is the board type. ()
- is the number of toy animals. ()
- is the greatest distance at which two toy animals can hear each other. ()
- is the largest value a coordinate can take. If then ; if then ; if then .
Each of the next lines gives the coordinates of one toy animal. On board a line contains integers separated by spaces: when , when , and when . Every coordinate is a natural number between and inclusive. Several animals may occupy the same cell.
Output
Print on the first line the number of pairs of toy animals that can hear each other.