Slate Modern (Small)
Time limit5sMemory limit512 MB
Given some pre-filled cells in an R by C grid with an edge-adjacency difference limit D, decide if the rest can be filled with positive integers and find the maximum total sum modulo 1e9+7.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, Math, Implementation
- Solved
- No attempts yet
Problem
The Slate Modern gallery shows only grayscale paintings that follow strict rules. A painting in this gallery must be a grid with rows and columns, and every cell is painted with a positive integer brightness value. So that a painting is not too jarring, any two cells that share an edge (sharing only a corner does not count) must have brightness values that differ by at most .
Your artist friend Cody-Jamal is working on a canvas for the gallery. Last night he filled in different cells with positive integer brightness values. He heard the gallery rules only today, and now he wants to know whether every remaining cell can be filled with a positive integer brightness value without breaking the rules. If the painting can be finished, he wants the sum of all brightness values to be as large as possible so that he saves black paint. Find that sum, or report that finishing the painting is impossible. The sum can be very large, so print it modulo the prime .
Input
The first line contains the number of test cases . test cases follow. Each test case begins with one line holding four integers , , , and . Then lines follow. The -th of them holds three integers , , and , meaning that the cell in row and column has brightness value . Rows and columns are numbered from 1.
Limits
- and for all
- for all . This upper bound applies only to the cells Cody-Jamal already painted. You may assign brightness values larger than to the other cells.
- , so at least one cell is empty.
- If then or , so all of the given cells are different.
Output
For each test case, print one line of the form Case #x: y, where x is the test case number starting from 1 and y is IMPOSSIBLE if the painting cannot be finished, and otherwise the maximum possible sum of all brightness values modulo the prime .
Hint
In the first test case the best way to finish the painting is
6 7 9
4 6 8
and the sum is 40.
In the second test case the best way is 2000000000 1000000000, whose sum is 3000000000. Modulo that is 999999986.
The third test case is impossible. Whatever value goes into the cell in row 2, it differs too much from at least one of its two painted neighbors.
The fourth test case is impossible because the two cells Cody-Jamal already painted have brightness values that are too far apart.