Manhattan Power Failure
InterviewTime limit1sMemory limit256 MB
Count the blocks linked by intact lines into regions and report how many regions hold no generator.
- Level
Easy3 of 10
- Topics
- Union-find, Graph
- Solved
- No attempts yet
Problem
A huge storm tore through Manhattan, destroying many power lines and leaving entire blocks without power. The first damage assessment produced a report showing which blocks are still connected by power lines and which are not. When two blocks are connected by a power line, one block having power means the other block has power too. A power line runs only between blocks that are adjacent horizontally or vertically. A quickly written list of the blocks that hold their own power generator, or that are connected to an external power source, is also available.
Emergency power lines have to go up so that every block of this grid city has power again. Find the smallest number of emergency power lines needed.
Input
The first line contains an integer , the number of test cases. Each test case is given as follows.
- One line with four integers , , , . and () are how many blocks the city is wide and long, so the city has blocks. () is the number of power generators, and () is the number of intact power lines between adjacent city blocks.
- lines, each with two integers () and (), meaning that block has its own power source or is connected to an external power source.
- lines, each with two integers (), () and a character , where is R or U. If is R, an intact power line runs between block and block . If is U, it runs between block and block . If then cannot be R, and if then cannot be U.
Output
For each test case, print one line with the smallest number of emergency power lines needed to connect every block to a power source.