#P3367. Union-Find Operations
Union-Find Operations
Union-Find Operations
You are given a union-find (disjoint set union) data structure. Your task is to implement two operations:
- Union: Merge the sets that contain two specified elements.
- Query: Determine if two elements are in the same set.
More formally, you start with \( n \) elements (numbered from 1 to \( n \)), each in its own set. There will be \( q \) operations. Each operation is either a union
or a query
. For a query operation, if the two elements are in the same set, output YES
; otherwise, output NO
.
The mathematical representation of the union-find data structure involves the following idea:
$$ \text{if } x,y \text{ are elements, then } find(x) = find(y) \Longleftrightarrow x \text{ and } y \text{ are in the same set.} $$inputFormat
The first line contains two integers \( n \) and \( q \) \( (1 \leq n, q \leq 10^5) \) representing the number of elements and the number of operations, respectively.
Each of the following \( q \) lines contains an operation in one of the following formats:
union x y
— Merge the sets containing elements \( x \) and \( y \).query x y
— Check if elements \( x \) and \( y \) belong to the same set.
It is guaranteed that \( 1 \leq x, y \leq n \).
outputFormat
For each query
operation, output a single line containing either YES
if the two elements are in the same set, or NO
otherwise.
sample
5 5
union 1 2
union 3 4
query 1 2
query 1 3
query 3 4
YES
NO
YES
</p>