Merging Communities

  • + 0 comments

    Java O(n) and O(A(n))

    public class Solution {
    
            static class DisjointSetUnion {
                private int[] parent;
                private int[] size;
    
                public DisjointSetUnion(int n) {
                    parent = new int[n + 1];
                    size = new int[n + 1];
                    for (int i = 1; i <= n; i++) {
                        parent[i] = i;
                        size[i] = 1;
                    }
                }
    
                public int find(int u) {
                    if (parent[u] != u) {
                        parent[u] = find(parent[u]);
                    }
                    return parent[u];
                }
    
                public void union(int u, int v) {
                    int rootU = find(u);
                    int rootV = find(v);
                    if (rootU != rootV) {
                        if (size[rootU] < size[rootV]) {
                            int temp = rootU;
                            rootU = rootV;
                            rootV = temp;
                        }
                        parent[rootV] = rootU;
                        size[rootU] += size[rootV];
                    }
                }
    
                public int getSize(int u) {
                    return size[find(u)];
                }
            }
    
            public static void main(String[] args) {
                Scanner scanner = new Scanner(System.in);
                int n = scanner.nextInt();
                int q = scanner.nextInt();
                DisjointSetUnion dsu = new DisjointSetUnion(n);
                StringBuilder output = new StringBuilder();
    
                for (int i = 0; i < q; i++) {
                    String query = scanner.next();
                    if (query.equals("M")) {
                        int u = scanner.nextInt();
                        int v = scanner.nextInt();
                        dsu.union(u, v);
                    } else if (query.equals("Q")) {
                        int u = scanner.nextInt();
                        output.append(dsu.getSize(u)).append("\n");
                    }
                }
                System.out.print(output);
                scanner.close();
            }
        }