Guest User

Untitled

a guest
Nov 23rd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. //Maciej Matuszewski
  2. #include <iostream>
  3.  
  4. typedef unsigned int uint;
  5. using namespace std;
  6.  
  7. #define xorSwap(a, b)\
  8. a ^= b;\
  9. b ^= a;\
  10. a ^= b;
  11.  
  12. #define sort2(a, b)\
  13. if (a > b) {xorSwap(a, b)}
  14.  
  15. #define sort3(a, b, c)\
  16. {\
  17. sort2(b, c)\
  18. sort2(a, c)\
  19. sort2(a, b)\
  20. }
  21.  
  22. #define sort4(a, b, c, d)\
  23. {\
  24. sort2(a, b) sort2(c, d)\
  25. sort2(a, c) sort2(b, d)\
  26. sort2(b, c)\
  27. }
  28.  
  29. #define sort5(a, b, c, d, e)\
  30. {\
  31. sort2(a, b) sort2(d, e)\
  32. sort2(c, e)\
  33. sort2(c, d) sort2(b, e)\
  34. sort2(a, d)\
  35. sort2(a, c) sort2(b, d)\
  36. sort2(b, c)\
  37. }
  38.  
  39. uint partition(uint t[], uint n, uint p)
  40. {
  41. uint q = 0;
  42. uint i;
  43. for (i = 0; i < n-1; ++i, ++q)
  44. {
  45. if (t[i] > p)
  46. {
  47. break;
  48. }
  49. else if (t[i] == p)
  50. {
  51. xorSwap(t[i], t[n-1])
  52. if (t[i] > p)
  53. break;
  54. }
  55. }
  56. for (; i < n-1; ++i)
  57. {
  58. if (t[i] < p)
  59. {
  60. xorSwap(t[i], t[q])
  61. ++q;
  62. }
  63. else if (t[i] == p)
  64. {
  65. xorSwap(t[i], t[n-1])
  66. if (t[i] < p)
  67. {
  68. xorSwap(t[i], t[q])
  69. ++q;
  70. }
  71. }
  72. }
  73. if (n-1 != q)
  74. xorSwap(t[n-1], t[q]);
  75. return q;
  76. }
  77.  
  78. uint select(uint t[], uint n, uint k)
  79. {
  80. switch(n)
  81. {
  82. case 1:
  83. return t[0];
  84. case 2:
  85. sort2(t[0], t[1])
  86. return t[k];
  87. case 3:
  88. sort3(t[0], t[1], t[2])
  89. return t[k];
  90. case 4:
  91. sort4(t[0], t[1], t[2], t[3])
  92. return t[k];
  93. case 5:
  94. sort5(t[0], t[1], t[2], t[3], t[4])
  95. return t[k];
  96. }
  97. uint num = n/5;
  98. for (uint i = 0; i < num; ++i)
  99. sort5(t[i], t[i+num], t[i+2*num], t[i+3*num], t[i+4*num]);
  100. switch(n%5)
  101. {
  102. case 1:
  103. case 2:
  104. xorSwap(t[n-1], t[3*num])
  105. break;
  106. case 3:
  107. sort3(t[n-3], t[n-2], t[n-1])
  108. xorSwap(t[n-2], t[3*num])
  109. break;
  110. case 4:
  111. sort4(t[n-4], t[n-3], t[n-2], t[n-1])
  112. xorSwap(t[n-3], t[3*num])
  113. break;
  114. }
  115. uint mnum = (n+4)/5;
  116. uint p = select(&t[2*num], mnum, mnum/2);
  117. uint x = partition(t, n, p);
  118. if (x == k)
  119. return t[x];
  120. else if (x > k)
  121. return select(t, x, k);
  122. else if (x < k)
  123. return select(&t[x+1], n-x-1, k-x-1);
  124. }
  125.  
  126. int main()
  127. {
  128. uint n;
  129. cin >> n;
  130. uint *t = new uint[n];
  131. for (uint i = 0; i < n; ++i)
  132. cin >> t[i];
  133. uint k;
  134. cin >> k;
  135. cout << select(t, n, k-1) << endl;
  136. return 0;
  137. }
Add Comment
Please, Sign In to add comment