Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
- public class DisjointSet {
- private Map<Long, Node> map = new HashMap<Long, Node>();
- private Map<Long, Integer> sizes = new HashMap<Long, Integer>();
- static class Node {
- int rank;
- long data;
- Node parent;
- Node(long data) {
- this(data, null, 0);
- }
- Node(long data, Node parent, int rank) {
- this.data = data;
- this.parent = parent;
- this.rank = rank;
- if(parent == null) {
- this.parent = this;
- }
- }
- }
- public void makeSet(long data) {
- Node n = new Node(data);
- map.put(data, n);
- sizes.put(data, 1);
- }
- public void union(long data1, long data2) {
- Node n1 = map.get(data1);
- Node n2 = map.get(data2);
- Node p1 = findSet(n1);
- Node p2 = findSet(n2);
- if(p1.data != p2.data) {
- int newSize = sizes.get(p1.data) + sizes.get(p2.data);
- if(p1.rank >= p2.rank) {
- p1.rank = p1.rank == p2.rank ? p1.rank + 1 : p1.rank;
- p2.parent = p1;
- sizes.put(p1.data, newSize);
- }
- else {
- p1.parent = p2;
- sizes.put(p2.data, newSize);
- }
- }
- }
- public long findSet(long data) {
- return findSet(map.get(data)).data;
- }
- public Node findSet(Node n) {
- Node p = n.parent;
- if(p == n) {
- return p;
- }
- // compression!
- n.parent = findSet(n.parent);
- return n.parent;
- }
- public int getSize(long data) {
- Node p = findSet(map.get(data));
- return sizes.get(p.data);
- }
- public static void main(String[] args) {
- DisjointSet d = new DisjointSet();
- Scanner s = new Scanner(System.in);
- int n = s.nextInt();
- int q = s.nextInt();
- for(int i = 1; i <= n; i++) {
- d.makeSet(i);
- }
- for(int i = 0; i < q; i++) {
- char type = s.next().charAt(0);
- switch(type) {
- case 'Q':
- System.out.println(d.getSize(s.nextLong()));
- break;
- case 'M':
- d.union(s.nextLong(), s.nextLong());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement