Under construction

Still being built. Things may change

Manhattan Power Failure

Interview

Time limit1sMemory limit256 MB

Summary
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 TT, the number of test cases. Each test case is given as follows.

  • One line with four integers nn, mm, pp, cc. nn and mm (1≤n,m≤1001 \le n, m \le 100) are how many blocks the city is wide and long, so the city has n×mn \times m blocks. pp (1≤p≤n⋅m1 \le p \le n \cdot m) is the number of power generators, and cc (1≤c≤2n⋅m−n−m1 \le c \le 2n \cdot m - n - m) is the number of intact power lines between adjacent city blocks.
  • pp lines, each with two integers xx (0≤x<n0 \le x < n) and yy (0≤y<m0 \le y < m), meaning that block (x,y)(x, y) has its own power source or is connected to an external power source.
  • cc lines, each with two integers xx (0≤x<n0 \le x < n), yy (0≤y<m0 \le y < m) and a character dd, where dd is R or U. If dd is R, an intact power line runs between block (x,y)(x, y) and block (x+1,y)(x + 1, y). If dd is U, it runs between block (x,y)(x, y) and block (x,y+1)(x, y + 1). If x=n−1x = n - 1 then dd cannot be R, and if y=m−1y = m - 1 then dd 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.

Examples1

  1. Example 1

    Input
    2
    2 3 2 3
    0 2
    1 1
    0 0 U
    0 2 R
    1 1 U
    2 4 2 6
    0 3
    1 0
    0 0 U
    0 1 U
    0 1 R
    0 2 R
    0 3 R
    1 1 U
    
    Expected output
    2
    1