#C8453. Count Same-Color Connected Components

    ID: 52437 Type: Default 1000ms 256MiB

Count Same-Color Connected Components

Count Same-Color Connected Components

You are given an undirected graph with \(n\) vertices and \(m\) edges. Each vertex is colored either black ('B') or white ('W'). Your task is to count the number of connected components in the graph such that all vertices in the component have the same color.

A connected component is a set of vertices where each vertex is reachable from any other vertex in the same component. In this problem, a component is considered valid if it is "monochrome", i.e. all its vertices share the same color.

Input Format: The input starts with an integer \(T\) representing the number of test cases. For each test case:

  • The first line contains two integers \(n\) and \(m\) — the number of vertices and edges.
  • The second line contains a string of length \(n\) consisting of characters 'B' and 'W', representing the color of each vertex. The vertices are 1-indexed.
  • The next \(m\) lines each contain two integers \(u\) and \(v\), indicating an undirected edge between vertices \(u\) and \(v\).

Output Format: For each test case, output a single integer on a new line representing the number of connected components that contain vertices of the same color only.

Note: The graph may be disconnected, and there may be components that consist of only one vertex.

The problem can be formally described as follows: Given a graph \(G=(V,E)\) and a color function \(c: V \to \{B, W\}\), find the number of connected subsets \(C \subseteq V\) such that for any two vertices \(u, v \in C\), \(u\) and \(v\) are connected in \(G\) and \(c(u)=c(v)\).

inputFormat

The input is read from the standard input. The first line contains an integer \(T\) denoting the number of test cases. Then for each test case:

  • The first line contains two integers \(n\) and \(m\) separated by a space.
  • The second line contains a string of length \(n\) composed of the characters 'B' and 'W', representing the colors of the vertices.
  • The next \(m\) lines each contain two integers \(u\) and \(v\), indicating an undirected edge connecting vertices \(u\) and \(v\).

It is guaranteed that the vertices are numbered from 1 to \(n\).

outputFormat

For each test case, output one integer on a new line, which is the count of connected components that are monochromatic.

## sample
2
6 5
BWBWBW
1 2
2 3
3 4
4 5
5 6
5 4
BBBBW
1 2
1 3
2 4
3 5
6

2

</p>