Handbags
Time limit11sMemory limit512 MB
A grid of villages sets prices from s source prices; report the maximum price and how many villages reach it.
- Level
Hard8 of 10
- Topics
- Shortest path, Graph, Math
- Solved
- No attempts yet
Problem
Handbags are a popular souvenir everywhere in the city of Manhattanila, because the city makes them itself.
Manhattanila has villages, locally called barangays, laid out neatly in an rectangular lattice. A village is named by two integers with and , its row number and its column number, both counted from 0.

Exactly of the villages make handbags. Call these the source villages. Every other village buys its handbags from a neighboring village. Two villages are neighbors when they share a boundary, so a village has up to four neighbors, one in each cardinal direction. A neighbor need not be a source village, so it may buy its own supply from another neighbor, and so on.
A source village makes handbags at a fixed price of its own. A village that buys from a neighbor selling at pesos sells at pesos. Every village pays as little as it can: it buys from the neighbor that sells cheapest, and a source village sells at its own price or at its cheapest neighbor's price plus 1, whichever is smaller. These rules give every village exactly one price.
A tourist comes to Manhattanila for souvenirs (pasalubong). To impress her friends she plans to say that she bought her handbags in the village where they cost the most, while she quietly buys them in the village where they cost the least. Answer her question: what is the highest price of a handbag in the city, and how many villages sell at that price?
Input
The first line contains , the number of test cases.
The first line of each test case contains three integers , and , where is the number of source villages. Each of the next lines contains three integers , and , meaning that village is a source village and sells its handbags at pesos. No pair appears twice in one test case.
Constraints
- The sum of over all test cases is at most .
Output
For each test case, print one line with two integers separated by a space:
- the highest price of a handbag in the city, and
- the number of villages that sell at that price.