Islands
Time limit3sMemory limit512 MB
For several nondecreasing sea levels, count the connected regions of cells whose height is above the water level.
- Level
Medium7 of 10
- Topics
- Union-find, Sorting, Graph, Implementation
- Solved
- No attempts yet
Problem
Deep in the Caribbean lies a rectangular island divided into an grid. Every grid cell has a fixed height measured in meters.
The sea level keeps rising: in year the sea level is exactly meters. The island is made of sponge, so water flows freely through it — a cell is flooded whenever its height is at most the current sea level. Cells that are not flooded and share a common edge belong to the same unflooded area (a connected region).
For each of several years, determine how many separate unflooded areas the island has.
The picture below shows a island; the numbers are the cell heights in meters and the unflooded cells are drawn darker. There are two unflooded areas in year 1 and three unflooded areas in year 2.
Input
The first line contains a positive integer (), the number of test cases. Each test case is given as follows.
The first line contains two integers and (), the dimensions of the island. The next lines each contain integers in the range , the heights of the cells. The next line contains an integer (). The last line contains integers with , the sea levels (years) to query.
Output
For each test case, print a single line with integers separated by single spaces, where is the number of unflooded areas when the sea level is .

