fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. public static int n = 7;
  12.  
  13. public static int[] parent = {0, 1, 2, 3, 4, 5, 6};
  14. public static int[] rank = {0, 0, 0, 0, 0, 0, 0};
  15.  
  16. public static int find(int node){
  17. if(parent[node] == node){
  18. return node;
  19. }else{
  20. int up = find(parent[node]);
  21. parent[node] = up;
  22. return parent[node];
  23. }
  24. }
  25.  
  26. public static void union(int a, int b){
  27.  
  28. int root1 = find(a);
  29. int root2 = find(b);
  30.  
  31. if(root1 == root2){
  32. return;
  33. }else{
  34. if(rank[root1] < rank[root2]){
  35. parent[root1] = parent[root2];
  36. }else if(rank[root1] > rank[root2]){
  37. parent[root2] = parent[root2];
  38. }else{
  39. parent[root1] = root2;
  40. int ranku = rank[root1];
  41. rank[root1] = ranku + 1;
  42. }
  43. }
  44. }
  45. public static void main (String[] args) throws java.lang.Exception
  46. {
  47. // your code goes here
  48.  
  49. union(1, 2);
  50. union(2, 3);
  51. union(5, 4);
  52.  
  53. System.out.print(find(4));
  54.  
  55.  
  56. }
  57. }
Success #stdin #stdout 0.08s 54564KB
stdin
Standard input is empty
stdout
4