#C6299. Kingdom Connectivity
Kingdom Connectivity
Kingdom Connectivity
You are given a kingdom represented as an undirected graph with n towns and initially m roads connecting some pairs of towns. The towns are numbered from 1 to n.
You will then process q queries of three types:
- Type 1:
1 u v
— Build a road between town u and town v if it does not already exist. - Type 2:
2 u v
— Destroy the road between town u and town v if it exists. - Type 3:
3
— Print the current number of connected components in the kingdom.
Note: After a road is removed, the structure of the connected components must be recalculated from the remaining roads. The input queries modify the graph sequentially. Use union-find (disjoint-set union) data structure for efficient processing, but note that removal may require a complete recomputation of the connectivity.
The formula for the number of connected components can be thought of as:
$$\text{components} = n - \text{(number of successful unions)}$$where a successful union merges two previously separate components.
inputFormat
The first line of input contains two integers n and m — the number of towns and the number of initial roads.
The next m lines each contain two integers u and v, denoting a road between towns u and v.
The following line contains an integer q — the number of queries.
Each of the next q lines represents a query in one of the following formats:
3
1 u v
2 u v
It is guaranteed that the queries are processed sequentially.
outputFormat
For each query of type 3
, output a single integer on its own line representing the current number of connected components in the kingdom.
5 4
1 2
2 3
3 4
4 5
5
3
2 2 3
3
1 2 5
3
1
2
1
</p>