Whac-a-Mole

Time limit1sMemory limit128 MB

Summary
Given each mole's position and time, find the maximum number of moles whacked while the hammer moves at most distance d between time steps.
Level

Medium7 of 10

Topics
Dynamic programming, Geometry, Bit manipulation
Solved
No attempts yet

Problem

While visiting a traveling fun fair you suddenly get the urge to beat the high score in the Whac-a-Mole game. The goal of Whac-a-Mole is to whack moles with a hammer. To make the job easier you have first consulted a fortune teller, and now you know the exact pattern in which the moles will appear.

The moles come out of holes located at the n2n^2 integer points (x,y)(x, y) satisfying 0≤x,y<n0 \le x, y < n in a two-dimensional coordinate system. At each time step some moles appear and then disappear again before the next time step. After the moles appear but before they disappear, you may move your hammer in a straight line to any point (x2,y2)(x_2, y_2) that is at Euclidean distance at most dd from its current position (x1,y1)(x_1, y_1). The hammer may only be moved to points with integer coordinates. A mole is whacked if the center of the hole it came out of lies on the segment between (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) (both endpoints included). Each whacked mole earns you one point. Before the first time step, you may place your hammer at any position you like.

Input

The input consists of several test cases. Each test case starts with a line containing three integers nn, dd and mm, where nn and dd are as described above and mm is the total number of moles that will appear (1≤n≤201 \le n \le 20, 1≤d≤51 \le d \le 5, and 1≤m≤10001 \le m \le 1000). Then follow mm lines, each containing three integers xx, yy and tt giving the position and time of the appearance of a mole (0≤x,y<n0 \le x, y < n and 1≤t≤101 \le t \le 10). No two moles will appear at the same place at the same time.

The input ends with a test case where n=d=m=0n = d = m = 0; this case must not be processed.

Output

For each test case, output a single line containing one integer: the maximum score you can achieve.

Examples4

  1. Example 1

    Input
    4 2 6
    0 0 1
    3 1 3
    0 1 2
    0 2 2
    1 0 2
    2 0 2
    5 4 3
    0 0 1
    1 2 1
    2 4 1
    0 0 0
    
    Expected output
    4
    2
    
  2. Example 2

    Input
    1 1 1
    0 0 1
    0 0 0
    
    Expected output
    1
    
  3. Example 3

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

    Input
    20 5 6
    0 0 1
    1 0 1
    2 0 1
    3 0 1
    4 0 1
    5 0 1
    0 0 0
    
    Expected output
    6