1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <bits/stdc++.h> using namespace std;
#ifndef _KTH_ #define _KTH_ #define ll int
template <typename T> bool compare(const T & t1, const T & t2) { return t1 < t2; }
template <typename T> T* FindKth(T *s, T *t, ll k, bool (*cmp)(const T &, const T &) = compare) { T *x = s + (rand()%(t-s)); T *y = s + (rand()%(t-s)); T *z = s + (rand()%(t-s)); if(cmp(*z,*x)) { swap(*x,*z); } if(cmp(*y,*x)) { swap(*x,*y); } if(cmp(*z,*y)) { swap(*y,*z); } swap(*y,*s); T *p = s + 1; T *lt = s, *gt = t-1; T pivot = *s; while(p <= gt) { if(cmp(*p,pivot)) { swap(*(lt++),*(p++)); } else if(cmp(pivot,*p)) { swap(*(gt--),*p); } else { p++; } } if(lt-s <= k && k < gt+1-s) { return lt; } else if(lt-s > k) { return FindKth(s,lt,k,cmp); } else { return FindKth(gt+1,t,k-(gt-s+1),cmp); } }
template <typename T> T* findKth(T *s, T *t, ll k, bool (*cmp)(const T &, const T &) = compare) { srand(time(NULL)); return FindKth(s,t,k,cmp); } #endif
|