ADVANCED DATA STRUCTURES PROGRAM • LEVEL 9 — DISJOINT SETS
Answer Offline Connectivity Queries
Learn how to answer offline connectivity queries using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Yes No Yes
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int parent[10], rank_value[10], set_size[10];
void initialize(int count) { for (int i = 0; i < count; i++) { parent[i] = i; rank_value[i] = 0; set_size[i] = 1; } }
int find_root(int value) { return parent[value] == value ? value : (parent[value] = find_root(parent[value])); }
void unite_rank(int first, int second)
{
first = find_root(first); second = find_root(second);
if (first == second) return;
if (rank_value[first] < rank_value[second]) { int temp = first; first = second; second = temp; }
parent[second] = first; set_size[first] += set_size[second];
if (rank_value[first] == rank_value[second]) rank_value[first]++;
}
int main(void)
{
initialize(6);
unite_rank(0, 1); unite_rank(1, 2); unite_rank(4, 5);
int queries[][2] = {{0, 2}, {0, 5}, {4, 5}};
for (int index = 0; index < 3; index++)
printf("%s%c", find_root(queries[index][0]) == find_root(queries[index][1]) ? "Yes" : "No", index == 2 ? '\n' : ' ');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Yes No Yes
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Compare compressed representatives for each pair after processing all unions.
- Display the computed result.
Compare compressed representatives for each pair after processing all unions.
EFFICIENCY
Time and space complexity
Time complexity
O(q alpha(n))
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
