Merging Communities

Sort by

recency

|

14 Discussions

|

  • + 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();
            }
        }
    
  • + 0 comments
    class UnionFind:
        def __init__(self, number_of_nodes):
            self.parent = [i for i in range(0, number_of_nodes+1)]
            self.rank = [1] * (number_of_nodes + 1)
            self.size = [1] * (number_of_nodes + 1)
        
        def find(self, node1):
            if self.parent[node1] == node1:
                return node1
            
            self.parent[node1] = self.find(self.parent[node1])
            return self.parent[node1]
                
        def union(self, node1, node2):
            root1, root2 = self.find(node1), self.find(node2)
            if root1 != root2:
                if self.rank[root1] < self.rank[root2]:
                    root1, root2 = root2, root1
                if self.rank[root1] == self.rank[root2]:
                    self.rank[root1] += 1
                self.parent[root2] = root1
                self.size[root1] = self.size[root1] + self.size[root2]
     
    inp_arr = input().split(' ')
    n, q = int(inp_arr[0]), int(inp_arr[1])
    
    uf = UnionFind(n)
    
    for i in range(q):
        inp_arr = input().split(' ')
        qtype = inp_arr[0]
        if qtype == 'Q':
            p = int(inp_arr[1])
            print(uf.size[uf.find(p)])
        else:
            p1, p2 = int(inp_arr[1]), int(inp_arr[2])
            uf.union(p1, p2)
    
  • + 0 comments

    Java Solution:

    public class Solution {
    
        public static int find(int v, int[] parent) {
            if(v == parent[v-1]) {
                return v;
            }
            parent[v-1] = find(parent[v-1], parent);
            return parent[v-1];
        }
        
        public static void union(int a, int b, int[] parent, int[] st) {
            int ca = find(a, parent);
            int cb = find(b, parent);
            if(ca == cb) {
                return;
            }
            st[cb-1] = st[ca-1] + st[cb-1];
            parent[ca-1] = cb;
        }
        
        public static void main(String[] args) throws IOException {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));;
            BufferedWriter wt = new BufferedWriter(new PrintWriter(System.out));
            
            String[] ins = rd.readLine().split(" ");
            
            int n = Integer.parseInt(ins[0]);
            int q = Integer.parseInt(ins[1]);
           
            int[] parent = new int[n + 1];
            int[] st = new int[n + 1];
            
            for (int i = 0; i < n; i++) {
                parent[i] = i+1;
                st[i] = 1;
                
            }
            
    
            for (int k = 0; k < q; k ++) {
                String[] in = rd.readLine().split(" ");
            
                switch (in[0]) {
                    case "M" : 
                        int i = Integer.parseInt(in[1]);
                        int j = Integer.parseInt(in[2]);
                        union(i, j, parent, st);
                        break;
                    case "Q" :
                        i = Integer.parseInt(in[1]);            
                        int p = find(i, parent);
                        int count = st[p - 1];
                        wt.write(count + "\n");
                        break;
                }
            }
            
            wt.flush();
            wt.close();
            rd.close();
        }
    }
    
  • + 0 comments

    Js

    function processData(input) {
        let inputs = input.split('\n');
        let n = parseInt(inputs.shift())
        const arrUnion = Array.from({ length: n + 1 }, (_, i) => i)
        const arrSize = Array(n + 1).fill(1);
        
        for (const query of inputs) {
            let command = query.split(' ')[0];
            let number1 = parseInt(query.split(' ')[1]);
            let number2 = parseInt(query.split(' ')[2]);
            if (command === 'Q') {
                let node = number1;
                while (arrUnion[node] !== node) {
                    node = arrUnion[arrUnion[node]]
                }
                console.log(arrSize[node]);
            } else if (command === 'M') {
                if (number1 === number2) {
                    continue;
                }
                let node1 = number1;
                let node2 = number2;
                while (arrUnion[node1] !== node1) {
                    node1 = arrUnion[arrUnion[node1]]
                }
                while (arrUnion[node2] !== node2) {
                    node2 = arrUnion[arrUnion[node2]]
                }
                if (node1 === node2) {
                    continue;
                }
                let [big, small] = arrSize[node1] >= arrSize[node2] ? [node1, node2] : [node2, node1];
                arrUnion[small] = big;
                arrSize[big] += arrSize[small];
            }
        } 
    } 
    
  • + 0 comments

    Solution written in Rust:

    use std::io::{self, BufRead};
    
    fn find(parent: &mut Vec<usize>, i: usize) -> usize {
        if parent[i] != i {
            parent[i] = find(parent, parent[i]);
        }
        parent[i]
    }
    
    fn union(parent: &mut Vec<usize>, size: &mut Vec<usize>, a: usize, b: usize) {
        let root_a = find(parent, a);
        let root_b = find(parent, b);
        if root_a != root_b {
            let (big, small) = if size[root_a] >= size[root_b] {
                (root_a, root_b)
            } else {
                (root_b, root_a)
            };
            parent[big] = small;
            size[small] += size[big];
        }
    }
    
    fn main() {
        let stdin = io::stdin();
        let mut lines = stdin.lock().lines().map(|line| line.unwrap());
    
        if let Some(line) = lines.next() {
            let mut input_iter = line.split_whitespace();
            let n: usize = input_iter.next().unwrap().parse().unwrap();
            let q: usize = input_iter.next().unwrap().parse().unwrap();
    
            let mut parent = (0..=n).collect::<Vec<usize>>();
            let mut size = vec![1; n + 1];
    
            for _ in 0..q {
                if let Some(query) = lines.next() {
                    let mut query_iter = query.split_whitespace();
                    let query_type = query_iter.next().unwrap();
                    let values: Vec<usize> = query_iter.map(|val| val.parse().unwrap()).collect();
    
                    if query_type == "M" {
                        let person1 = values[0];
                        let person2 = values[1];
                        union(&mut parent, &mut size, person1, person2);
                    } else if query_type == "Q" {
                        let person = values[0];
                        let root = find(&mut parent, person);
                        println!("{}", size[root]);
                    }
                }
            }
        }
    }