Fill a huge R by C grid with positive integers so adjacent cells differ by at most D, matching N fixed cells, maximizing the total sum or reporting impossibility.
Hard9GraphShortest pathMathImplementationNo attempts yetTime limit80sMemory limit512 MBThe Slate Modern gallery shows only grayscale paintings. Every painting in the gallery must be a grid with R rows and C columns, and each cell is painted with a positive integer brightness value. So that the art is not too startling, two cells that share an edge must have brightness values that differ by at most D. Cells that touch only at a corner are not restricted.
Last night your artist friend Cody-Jamal picked N different cells and filled each of them with a positive integer brightness value. You told him the gallery rules only today, and now he wants to know whether the remaining cells can all be filled with positive integer brightness values so that the painting obeys the rules. If that is possible, he wants the sum of all brightness values to be as large as possible, to save his black paint. The sum can be very large, so report it modulo the prime 109+7.
The first line contains the number of test cases T.
The first line of each test case contains four integers R, C, N, and D. Then N lines follow. The i-th of them contains three integers Ri, Ci, and Bi, which mean that the cell in row Ri and column Ci already has brightness value Bi. Rows and columns are numbered starting from 1.
For each test case, print one line in the form Case #x: y, where x is the test case number starting from 1. If the painting cannot be completed, y is IMPOSSIBLE. Otherwise y is the maximum possible sum of all brightness values modulo 109+7.
In test case 1 of the first example, one optimal painting is shown below, and its sum is 40.
6 7 9
4 6 8
In test case 2 the best painting is 2000000000 1000000000, whose sum is 3000000000. Modulo 109+7 that is 999999986.
Test case 3 cannot be completed. Whatever value you choose for the cell in row 2, it differs too much from at least one of the two painted cells above and below it.
In test case 4 the two cells Cody-Jamal already painted have brightness values that are too far apart, so the painting cannot be continued.