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. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Integer[] arr = {1, 4, 3, 2, 5};
  13. System.out.println(pairsCount(arr));
  14. }
  15.  
  16. static class Node
  17. {
  18. int value;
  19. Node left, right;
  20. int rc; // right count
  21. int ic; // duplicate count
  22.  
  23. Node(int value)
  24. {
  25. this.value = value;
  26. }
  27. }
  28.  
  29. static int pairsCount(Integer[] arr)
  30. {
  31. int count = 0;
  32. Node root = new Node(arr[0]);
  33. for(int i=1; i<arr.length; i++)
  34. {
  35. count += insert(root, arr[i]);
  36. }
  37. return count;
  38. }
  39.  
  40. static int insert(Node n, int v)
  41. {
  42. if(v < n.value)
  43. {
  44. if(n.left == null)
  45. {
  46. n.left = new Node(v);
  47. return 1 + n.rc + n.ic;
  48. }
  49. return 1 + n.rc + n.ic + insert(n.left, v);
  50. }
  51. else if(v > n.value)
  52. {
  53. if(n.right == null)
  54. {
  55. n.right = new Node(v);
  56. n.rc = 1;
  57. return 0;
  58. }
  59. n.rc += 1;
  60. return insert(n.right, v);
  61. }
  62. else
  63. {
  64. n.ic += 1;
  65. return n.rc;
  66. }
  67. }
  68. }
Success #stdin #stdout 0.07s 47056KB
stdin
Standard input is empty
stdout
3