using System; using System.Collections.Generic; class GfG { // Find the representative of the set that x belongs to static int Find(int i, int[] parent) { int root = parent[i]; if (parent[root] != root) { return parent[i] = Find(root, parent); } return root; } // Union of sets containing x and y static void UnionSets(int x, int y, int[] rank, int[] parent) { int xRoot = Find(x, parent); int yRoot = Find(y, parent); // If they are in the same set, no need to union if (xRoot == yRoot) return; // Union by rank if (rank[xRoot] < rank[yRoot]) { parent[xRoot] = yRoot; } else if (rank[yRoot] < rank[xRoot]) { parent[yRoot] = xRoot; } else { parent[yRoot] = xRoot; rank[xRoot]++; } } static List<bool> IncrementalQueries(int V, int[,] queries) { int[] rank = new int[V]; int[] parent = new int[V]; for (int i = 0; i < V; i++) parent[i] = i; List<bool> res = new List<bool>(); for (int i = 0; i < queries.GetLength(0); i++) { int q = queries[i, 0], u = queries[i, 1], v = queries[i, 2]; // For union query if (q == 1) { UnionSets(u, v, rank, parent); } // Check if connected else { // If parents are same, then // connected, otherwise not if (Find(u, parent) == Find(v, parent)) { res.Add(true); } else { res.Add(false); } } } return res; } static void Main() { int V = 5; int[,] queries = { {1, 0, 1}, {2, 0, 1}, {2, 1, 2}, {1, 0, 2}, {2, 1, 2}, {1, 3, 4}, {2, 2, 4}, {1, 1, 3}, {2, 2, 4} }; List<bool> res = IncrementalQueries(V, queries); foreach (bool val in res) { if (val) Console.Write("true "); else Console.Write("false "); } Console.WriteLine(); } }