#K52197. Graph Connected Components
Graph Connected Components
Graph Connected Components
You are given a series of operations on an initially empty undirected graph. There are two types of operations:
ADD u v
: Add an undirected edge between nodes u and v. If a node has not been seen before, it is created. Note that adding an edge between a node and itself creates an isolated node (self-loop is allowed).COUNT
: Output the current number of connected components in the graph. A connected component is defined as a maximal set of nodes such that there exists a path between every pair of nodes in that set.
Your task is to process the operations in the order they appear. For every COUNT
operation, print the number of connected components at that moment. All input is read from standard input and all output should be written to standard output.
The connectivity can be mathematically described as: two nodes u and v are in the same component if there exists a sequence of nodes u = x0, x1, ..., xk = v such that for every adjacent pair (xi, xi+1) there is an edge, i.e. edge(xi, xi+1) exists. In LaTeX format, this condition is given by:
$$ \text{For } u, v \in V, \ u \sim v \iff \exists\, (x_0, x_1, \ldots, x_k) \text{ with } x_0=u,\ x_k=v \text{ and } \forall i,\ (x_i,x_{i+1}) \in E. $$inputFormat
The first line of input contains a single integer T
indicating the number of operations. The following T
lines each contain an operation in one of the two formats:
ADD u v
: where u and v are integers.COUNT
All input should be read from stdin.
outputFormat
For each COUNT
operation encountered in the input, output a single line with the current number of connected components. The output should be written to stdout.
4
COUNT
ADD 1 2
COUNT
COUNT
0
1
1
</p>