Merging Communities

  • + 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();
        }
    }