Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Maciej Matuszewski
- #include <iostream>
- typedef unsigned int uint;
- using namespace std;
- #define xorSwap(a, b)\
- a ^= b;\
- b ^= a;\
- a ^= b;
- #define sort2(a, b)\
- if (a > b) {xorSwap(a, b)}
- #define sort3(a, b, c)\
- {\
- sort2(b, c)\
- sort2(a, c)\
- sort2(a, b)\
- }
- #define sort4(a, b, c, d)\
- {\
- sort2(a, b) sort2(c, d)\
- sort2(a, c) sort2(b, d)\
- sort2(b, c)\
- }
- #define sort5(a, b, c, d, e)\
- {\
- sort2(a, b) sort2(d, e)\
- sort2(c, e)\
- sort2(c, d) sort2(b, e)\
- sort2(a, d)\
- sort2(a, c) sort2(b, d)\
- sort2(b, c)\
- }
- uint partition(uint t[], uint n, uint p)
- {
- uint q = 0;
- uint i;
- for (i = 0; i < n-1; ++i, ++q)
- {
- if (t[i] > p)
- {
- break;
- }
- else if (t[i] == p)
- {
- xorSwap(t[i], t[n-1])
- if (t[i] > p)
- break;
- }
- }
- for (; i < n-1; ++i)
- {
- if (t[i] < p)
- {
- xorSwap(t[i], t[q])
- ++q;
- }
- else if (t[i] == p)
- {
- xorSwap(t[i], t[n-1])
- if (t[i] < p)
- {
- xorSwap(t[i], t[q])
- ++q;
- }
- }
- }
- if (n-1 != q)
- xorSwap(t[n-1], t[q]);
- return q;
- }
- uint select(uint t[], uint n, uint k)
- {
- switch(n)
- {
- case 1:
- return t[0];
- case 2:
- sort2(t[0], t[1])
- return t[k];
- case 3:
- sort3(t[0], t[1], t[2])
- return t[k];
- case 4:
- sort4(t[0], t[1], t[2], t[3])
- return t[k];
- case 5:
- sort5(t[0], t[1], t[2], t[3], t[4])
- return t[k];
- }
- uint num = n/5;
- for (uint i = 0; i < num; ++i)
- sort5(t[i], t[i+num], t[i+2*num], t[i+3*num], t[i+4*num]);
- switch(n%5)
- {
- case 1:
- case 2:
- xorSwap(t[n-1], t[3*num])
- break;
- case 3:
- sort3(t[n-3], t[n-2], t[n-1])
- xorSwap(t[n-2], t[3*num])
- break;
- case 4:
- sort4(t[n-4], t[n-3], t[n-2], t[n-1])
- xorSwap(t[n-3], t[3*num])
- break;
- }
- uint mnum = (n+4)/5;
- uint p = select(&t[2*num], mnum, mnum/2);
- uint x = partition(t, n, p);
- if (x == k)
- return t[x];
- else if (x > k)
- return select(t, x, k);
- else if (x < k)
- return select(&t[x+1], n-x-1, k-x-1);
- }
- int main()
- {
- uint n;
- cin >> n;
- uint *t = new uint[n];
- for (uint i = 0; i < n; ++i)
- cin >> t[i];
- uint k;
- cin >> k;
- cout << select(t, n, k-1) << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment