返回上页
块状链表
C++template <class T>
class BlockList {
private:
int sz, lim;
list<vector<T>> lst;
inline void init() {
vector<T> tmp = {numeric_limits<T>::max()};
lst.emplace_back(tmp);
}
auto find(const T& val) {
for (auto it = lst.begin(); it != lst.end(); it++) {
if (it->back() >= val) return it;
}
throw -1;
}
public:
BlockList() : sz(0) {init();}
explicit BlockList(int _lim) : sz(0), lim(_lim) {init();}
BlockList(const T* a, int n) : sz(0), lim(sqrt(n)) {
init();
for (int i = 1; i <= n; i++) insert(a[i]);
}
int size() const {return sz;}
bool empty() const {return sz == 0;}
void insert(const T& val) {
auto it = find(val);
it->emplace(lower_bound(it->begin(), it->end(), val), val), sz++;
if ((int) it->size() > lim) {
lst.emplace(next(it), it->begin() + (lim >> 1), it->end());
it->erase(it->begin() + (lim >> 1), it->end());
}
}
void remove(const T& val) {
auto it = find(val);
it->erase(lower_bound(it->begin(), it->end(), val)), sz--;
if (it->empty()) lst.erase(it);
}
T kth(int k) const {
for (auto arr : lst) {
if ((int) arr.size() > k) return arr[k];
k -= arr.size();
}
return T();
}
T operator[] (int k) const {return kth(k);}
int rank(const T& val) const {
int cnt = 0;
for (auto arr : lst) {
if (arr.back() >= val) return cnt + lower_bound(arr.begin(), arr.end(), val) - arr.begin();
cnt += arr.size();
}
return sz;
}
T predecessor(const T& val) {
auto it = find(val), it2 = lower_bound(it->begin(), it->end(), val);
if (it2 == it->begin()) return (--it)->back();
return *(--it2);
}
T successor(const T& val) {
auto it = find(val), it2 = upper_bound(it->begin(), it->end(), val);
if (it2 == it->end()) return (++it)->front();
return *it2;
}
};