#K95187. Union-Find Queries
Union-Find Queries
Union-Find Queries
You are given a set of \( n \) elements (numbered from 1 to \( n \)) and \( q \) queries. There are two types of queries:
- Union Query: "1 u v" – Merge (union) the sets containing elements \( u \) and \( v \).
- Find Query: "2 u v" – Check if elements \( u \) and \( v \) belong to the same set. Print
YES
if they are in the same set, orNO
otherwise.
The operations should be efficiently handled using the Union-Find (Disjoint Set Union) data structure. In particular, implement find
with path compression and union
by rank to ensure optimal performance.
Input Format: The first line contains an integer \( n \) (the number of elements). The second line contains an integer \( q \) (the number of queries). Each of the next \( q \) lines contains three integers representing a query in one of the two forms described above.
Output Format: For each find query (queries of type 2), output a single line with either YES
or NO
depending on whether the two queried elements are in the same set.
inputFormat
The input is read from standard input. It starts with two integers \( n \) and \( q \) in separate lines (or space-separated in the same line), where \( n \) is the number of elements and \( q \) is the number of queries. This is followed by \( q \) lines, each containing three integers:
- If the query starts with 1, it is a union operation followed by two integers \( u \) and \( v \).
- If the query starts with 2, it is a find operation followed by two integers \( u \) and \( v \) for which you must determine if they belong to the same set.
outputFormat
The output is written to standard output. For each query of type 2, print a line containing YES
if \( u \) and \( v \) are in the same set; otherwise, print NO
.
5
6
1 1 2
2 1 2
1 3 4
2 1 3
1 2 3
2 1 4
YES
NO
YES
</p>