跳到正文

个人记录

神秘set

zhchz约 73 分钟
原文

这是 2026年2月8日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年12月18日
收录
2026年2月8日
更新
2026年11月14日
篇幅
约 73 分钟

版本

  1. v2当前
  2. v1

Source: paste by stripe_python

O(qn)O(q\sqrt{n}),但跑的飞快。 改了一些错误。

Compressed
C++
#ifndef SPN_SET_H
#define SPN_SET_H
#include<vector>
#include<utility>
#include<algorithm>
#include<stdexcept>
#include<functional>
#include<iterator>
template<class T,class Cmp,bool Unique>class spn_set_base{private:static constexpr size_t _load=150;Cmp cmp;size_t _size;std::vector<std::vector<T>>lists;std::vector<T>maxes;std::vector<size_t>index;static size_t floor_log2(size_t n){return __lg(n);}void build();std::pair<size_t,size_t>pos(size_t);size_t loc(size_t,size_t);void split(size_t);void merge(size_t);void erase(size_t,size_t);public:spn_set_base():cmp(),_size(0){}template<class It>spn_set_base(const It&_begin,const It&_end):cmp(),_size(0){extend(_begin,_end);}class iterator;iterator begin();iterator end();iterator get(size_t);size_t size()const noexcept;bool empty()const noexcept;void reserve(size_t);void clear()noexcept;void shrink_to_fit()noexcept;template<class It>void extend(const It&,const It&);template<class It>void from_sorted(const It&,const It&);bool insert(const T&);bool erase(const T&);void erase(const iterator&);T kth(size_t);T operator[](size_t);T back()const;size_t lower_bound(const T&);size_t upper_bound(const T&);size_t count(const T&);bool contains(const T&);T precursor(const T&);T successor(const T&);T strict_precursor(const T&);T strict_successor(const T&);void swap(spn_set_base&);void join(spn_set_base&other,bool keep_source=false);bool operator==(const spn_set_base&)const;bool operator!=(const spn_set_base&)const;};template<class T,class Cmp,bool Unique>class spn_set_base<T,Cmp,Unique>::iterator{private:spn_set_base<T,Cmp,Unique>*set;size_t pos,idx;iterator():set(nullptr),pos(-1),idx(-1){}iterator(spn_set_base<T,Cmp,Unique>*_set,size_t _pos,size_t _idx):set(_set),pos(_pos),idx(_idx){}friend class spn_set_base;public:using value_type=T;using difference_type=std::ptrdiff_t;using pointer=const T*;using reference=const T&;using iterator_category=std::bidirectional_iterator_tag;iterator(const iterator&other)=default;iterator&operator=(const iterator&other)=default;operator size_t(){return set->loc(pos,idx);}const T&operator*()const{return set->lists[pos][idx];}const T*operator->()const{return&set->lists[pos][idx];}iterator&operator++(){if(pos>=set->lists.size())return*this;if(++idx>=set->lists[pos].size()){pos++;idx=0;}return*this;}iterator&operator--(){if(pos==0&&idx==0)return*this;if(pos>=set->lists.size()){pos=set->lists.size()-1;idx=set->lists[pos].size()-1;}else if(idx==0){pos--;idx=set->lists[pos].size()-1;}else{idx--;}return*this;}iterator operator++(int){iterator temp=*this;++*this;return temp;}iterator operator--(int){iterator temp=*this;--*this;return temp;}bool operator==(const iterator&other)const{return set==other.set&&pos==other.pos&&idx==other.idx;}bool operator!=(const iterator&other)const{return!(*this==other);}};template<class T,class Cmp,bool Unique>typename spn_set_base<T,Cmp,Unique>::iterator spn_set_base<T,Cmp,Unique>::begin(){return iterator(this,0,0);}template<class T,class Cmp,bool Unique>typename spn_set_base<T,Cmp,Unique>::iterator spn_set_base<T,Cmp,Unique>::end(){return iterator(this,lists.size(),0);}template<class T,class Cmp,bool Unique>typename spn_set_base<T,Cmp,Unique>::iterator spn_set_base<T,Cmp,Unique>::get(size_t idx){if(idx>=_size)throw std::out_of_range("index out of range");const auto&[a,b]=pos(idx);return iterator(this,a,b);}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::build(){size_t n=lists.size();index.assign(n,0);for(size_t i=1;i<n;i++){index[i]+=lists[i-1].size();size_t x=i+(i&-i);if(x<n)index[x]+=index[i];}}template<class T,class Cmp,bool Unique>std::pair<size_t,size_t>spn_set_base<T,Cmp,Unique>::pos(size_t idx){if(idx<lists[0].size())return{0,idx};if(index.empty())build();size_t n=index.size(),p=0;for(size_t i=floor_log2(n);i!=(size_t)-1;i--){size_t x=p+(1<<i);if(x<n&&idx>=index[x])idx-=index[x],p=x;}return{p,idx};}template<class T,class Cmp,bool Unique>size_t spn_set_base<T,Cmp,Unique>::loc(size_t pos,size_t idx){if(pos==0)return idx;if(index.empty())build();while(pos>0)idx+=index[pos],pos&=pos-1;return idx;}template<class T,class Cmp,bool Unique>size_t spn_set_base<T,Cmp,Unique>::size()const noexcept{return _size;}template<class T,class Cmp,bool Unique>bool spn_set_base<T,Cmp,Unique>::empty()const noexcept{return maxes.empty();}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::clear()noexcept{_size=0,lists.clear(),maxes.clear(),index.clear();}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::shrink_to_fit()noexcept{lists.shrink_to_fit(),maxes.shrink_to_fit(),index.shrink_to_fit();}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::reserve(size_t len){lists.reserve(len/_load+1),maxes.reserve(len/_load+1);}template<class T,class Cmp,bool Unique>bool spn_set_base<T,Cmp,Unique>::insert(const T&val){if(maxes.empty()){lists.emplace_back(1,val),maxes.emplace_back(val),_size++;return true;}size_t pos=std::upper_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();auto equals=[this](const T&a,const T&b){return!cmp(a,b)&&!cmp(b,a);};if(pos==maxes.size()){if(Unique&&equals(val,maxes.back()))return false;pos--,lists[pos].emplace_back(val),maxes[pos]=val;}else{auto it=std::upper_bound(lists[pos].begin(),lists[pos].end(),val,cmp);if(Unique){if(it!=lists[pos].begin()){if(equals(val,*std::prev(it)))return false;}else if(pos>0){if(equals(val,lists[pos-1].back()))return false;}}lists[pos].insert(it,val);}_size++,split(pos);return true;}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::split(size_t pos){if(lists[pos].size()>(_load<<1)){std::vector<T>half(lists[pos].begin()+_load,lists[pos].end());lists[pos].erase(lists[pos].begin()+_load,lists[pos].end());maxes[pos]=lists[pos].back();lists.insert(lists.begin()+pos+1,half);maxes.insert(maxes.begin()+pos+1,half.back());index.clear();}else if(!index.empty()){size_t n=index.size();for(size_t i=pos+1;i<n;i+=(i&-i))index[i]++;}}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::merge(size_t pos){lists[pos-1].insert(lists[pos-1].end(),lists[pos].begin(),lists[pos].end());maxes[pos-1]=lists[pos-1].back();lists.erase(lists.begin()+pos),maxes.erase(maxes.begin()+pos),index.clear();}template<class T,class Cmp,bool Unique>template<class It>void spn_set_base<T,Cmp,Unique>::extend(const It&_begin,const It&_end){ptrdiff_t len=std::distance(_begin,_end);if((len<<2)<(ptrdiff_t)_size){for(It it=_begin;it!=_end;it++)insert(*it);return;}std::vector<T>a(_begin,_end);for(const std::vector<T>&vec:lists)a.insert(a.end(),vec.begin(),vec.end());std::sort(a.begin(),a.end(),cmp);if(Unique){auto last=std::unique(a.begin(),a.end(),[this](const T&x,const T&y){return!cmp(x,y)&&!cmp(y,x);});a.erase(last,a.end());}clear(),_size=a.size();for(size_t i=0;i<_size;i+=_load){lists.emplace_back(a.begin()+i,a.begin()+std::min(_size,i+_load));maxes.emplace_back(lists.back().back());}}template<class T,class Cmp,bool Unique>template<class It>void spn_set_base<T,Cmp,Unique>::from_sorted(const It&_begin,const It&_end){std::vector<T>a(_begin,_end);if(Unique){auto last=std::unique(a.begin(),a.end(),[this](const T&x,const T&y){return!cmp(x,y)&&!cmp(y,x);});a.erase(last,a.end());}clear(),_size=a.size();for(size_t i=0;i<_size;i+=_load){lists.emplace_back(a.begin()+i,a.begin()+std::min(_size,i+_load));maxes.emplace_back(lists.back().back());}}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::erase(size_t pos,size_t idx){lists[pos].erase(lists[pos].begin()+idx),_size--;size_t len=lists[pos].size();if(len>(_load>>1)){maxes[pos]=lists[pos].back();if(!index.empty()){size_t idx_n=index.size();for(size_t i=pos+1;i<idx_n;i+=(i&-i))index[i]--;}}else if(lists.size()>1){if(pos==0)pos++;merge(pos),split(pos-1);}else if(len>0){maxes[pos]=lists[pos].back();}else{lists.erase(lists.begin()+pos),maxes.erase(maxes.begin()+pos),index.clear();}}template<class T,class Cmp,bool Unique>bool spn_set_base<T,Cmp,Unique>::erase(const T&val){if(maxes.empty())return false;size_t pos=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())return false;size_t idx=std::lower_bound(lists[pos].begin(),lists[pos].end(),val,cmp)-lists[pos].begin();if(idx>=lists[pos].size()||cmp(lists[pos][idx],val)||cmp(val,lists[pos][idx]))return false;erase(pos,idx);return true;}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::erase(const iterator&it){erase(it.pos,it.idx);}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::kth(size_t k){if(k>=_size)throw std::out_of_range("index out of range");const auto&[a,b]=pos(k);return lists[a][b];}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::operator[](size_t k){return kth(k);}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::back()const{if(maxes.empty())throw std::out_of_range("index out of range");return maxes.back();}template<class T,class Cmp,bool Unique>size_t spn_set_base<T,Cmp,Unique>::lower_bound(const T&val){if(maxes.empty())return 0;size_t pos=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())return _size;return loc(pos,std::lower_bound(lists[pos].begin(),lists[pos].end(),val,cmp)-lists[pos].begin());}template<class T,class Cmp,bool Unique>size_t spn_set_base<T,Cmp,Unique>::upper_bound(const T&val){if(maxes.empty())return 0;size_t pos=std::upper_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())return _size;return loc(pos,std::upper_bound(lists[pos].begin(),lists[pos].end(),val,cmp)-lists[pos].begin());}template<class T,class Cmp,bool Unique>bool spn_set_base<T,Cmp,Unique>::contains(const T&val){if(maxes.empty())return false;size_t pos=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())return false;size_t idx=std::lower_bound(lists[pos].begin(),lists[pos].end(),val,cmp)-lists[pos].begin();if(idx>=lists[pos].size())return false;return!cmp(val,lists[pos][idx])&&!cmp(lists[pos][idx],val);}template<class T,class Cmp,bool Unique>size_t spn_set_base<T,Cmp,Unique>::count(const T&val){if(Unique)return contains(val);if(maxes.empty())return 0;size_t l=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(l==maxes.size())return 0;size_t r=std::upper_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();size_t x=std::lower_bound(lists[l].begin(),lists[l].end(),val,cmp)-lists[l].begin();if(r==maxes.size())return _size-loc(l,x);size_t y=std::upper_bound(lists[r].begin(),lists[r].end(),val,cmp)-lists[r].begin();if(l==r)return y-x;return loc(r,y)-loc(l,x);}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::precursor(const T&val){if(maxes.empty())throw std::out_of_range("precursor not found");size_t pos=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())return maxes.back();auto it=std::lower_bound(lists[pos].begin(),lists[pos].end(),val,cmp);if(it!=lists[pos].end()&&!cmp(val,*it)&&!cmp(*it,val))return*it;if(it!=lists[pos].begin())return*std::prev(it);if(pos==0)throw std::out_of_range("precursor not found");return maxes[pos-1];}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::successor(const T&val){if(maxes.empty())throw std::out_of_range("successor not found");size_t pos=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())throw std::out_of_range("successor not found");auto it=std::lower_bound(lists[pos].begin(),lists[pos].end(),val,cmp);if(it!=lists[pos].end())return*it;if(pos+1==maxes.size())throw std::out_of_range("successor not found");return lists[pos+1][0];}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::strict_precursor(const T&val){if(maxes.empty())throw std::out_of_range("precursor not found");if(cmp(maxes.back(),val))return maxes.back();size_t pos=std::lower_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())throw std::out_of_range("precursor not found");auto it=std::lower_bound(lists[pos].begin(),lists[pos].end(),val,cmp);if(it!=lists[pos].begin())return*std::prev(it);if(pos==0)throw std::out_of_range("precursor not found");return maxes[pos-1];}template<class T,class Cmp,bool Unique>T spn_set_base<T,Cmp,Unique>::strict_successor(const T&val){if(maxes.empty())throw std::out_of_range("successor not found");size_t pos=std::upper_bound(maxes.begin(),maxes.end(),val,cmp)-maxes.begin();if(pos==maxes.size())throw std::out_of_range("successor not found");auto it=std::upper_bound(lists[pos].begin(),lists[pos].end(),val,cmp);if(it==lists[pos].end())throw std::out_of_range("successor not found");return*it;}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::swap(spn_set_base&other){std::swap(_size,other._size);lists.swap(other.lists),maxes.swap(other.maxes),index.swap(other.index);}template<class T,class Cmp,bool Unique>void spn_set_base<T,Cmp,Unique>::join(spn_set_base&other,bool keep_source){if(this==&other)return;if(other.empty())return;if(empty()){if(keep_source){lists=other.lists;maxes=other.maxes;index=other.index;_size=other._size;}else{swap(other);}return;}bool disjoint_append=false;if(Unique){if(cmp(maxes.back(),other.lists[0].front()))disjoint_append=true;}else{if(!cmp(other.lists[0].front(),maxes.back()))disjoint_append=true;}if(disjoint_append){if(keep_source){lists.reserve(lists.size()+other.lists.size());maxes.reserve(maxes.size()+other.maxes.size());for(const auto&vec:other.lists){lists.push_back(vec);maxes.push_back(vec.back());}}else{for(auto&vec:other.lists){lists.push_back(std::move(vec));maxes.push_back(lists.back().back());}}_size+=other._size;index.clear();if(!keep_source)other.clear();return;}if(other._size*8<_size){for(const auto&block:other.lists)for(const auto&val:block)insert(val);if(!keep_source)other.clear();return;}std::vector<T>flat_a;flat_a.reserve(_size);for(auto&vec:lists)flat_a.insert(flat_a.end(),std::make_move_iterator(vec.begin()),std::make_move_iterator(vec.end()));std::vector<T>flat_b;flat_b.reserve(other._size);if(keep_source){for(const auto&vec:other.lists)flat_b.insert(flat_b.end(),vec.begin(),vec.end());}else{for(auto&vec:other.lists)flat_b.insert(flat_b.end(),std::make_move_iterator(vec.begin()),std::make_move_iterator(vec.end()));}std::vector<T>merged;merged.reserve(_size+other._size);std::merge(std::make_move_iterator(flat_a.begin()),std::make_move_iterator(flat_a.end()),std::make_move_iterator(flat_b.begin()),std::make_move_iterator(flat_b.end()),std::back_inserter(merged),cmp);if(Unique){auto last=std::unique(merged.begin(),merged.end(),[this](const T&a,const T&b){return!cmp(a,b)&&!cmp(b,a);});merged.erase(last,merged.end());}from_sorted(merged.begin(),merged.end());if(!keep_source)other.clear();}template<class T,class Cmp,bool Unique>bool spn_set_base<T,Cmp,Unique>::operator==(const spn_set_base&other)const{if(_size!=other._size)return false;size_t pos1=0,idx1=0,pos2=0,idx2=0;while(pos1<lists.size()&&pos2<other.lists.size()){if(cmp(lists[pos1][idx1],other.lists[pos2][idx2])||cmp(other.lists[pos2][idx2],lists[pos1][idx1]))return false;idx1++,idx2++;if(idx1>=lists[pos1].size())pos1++,idx1=0;if(idx2>=other.lists[pos2].size())pos2++,idx2=0;}return true;}template<class T,class Cmp,bool Unique>bool spn_set_base<T,Cmp,Unique>::operator!=(const spn_set_base&other)const{return!(*this==other);}template<class T,class Cmp=std::less<T>>using spn_set=spn_set_base<T,Cmp,true>;template<class T,class Cmp=std::less<T>>using spn_multiset=spn_set_base<T,Cmp,false>;template<typename T>std::ostream&operator<<(std::ostream&os,spn_set<T>&s){os<<"{ ";std::string sep;for(auto it=s.begin();it!=s.end();++it)os<<sep<<(*it),sep=", ";return os<<" }";}template<typename T>std::ostream&operator<<(std::ostream&os,spn_multiset<T>&s){os<<"{ ";std::string sep;for(auto it=s.begin();it!=s.end();++it)os<<sep<<(*it),sep=", ";return os<<" }";}
#endif
Code
C++
#ifndef SPN_SET_H
#define SPN_SET_H

#include <vector>
#include <utility>
#include <algorithm>
#include <stdexcept>
#include <functional>
#include <iterator>

template <class T, class Cmp, bool Unique>
class spn_set_base {
private:
	static constexpr size_t     _load = 150;
	Cmp                         cmp;
	size_t                      _size;
	std::vector<std::vector<T>> lists;
	std::vector<T>              maxes;
	std::vector<size_t>         index;
	
	static size_t floor_log2(size_t n) {
		return __lg(n);
	}
	
	void                      build ()               ;
	std::pair<size_t, size_t> pos   (size_t)         ;
	size_t                    loc   (size_t, size_t) ;
	void                      split (size_t)         ;
	void                      merge (size_t)         ;
	void                      erase (size_t, size_t) ;
public:
	spn_set_base() : cmp(), _size(0) {}
	template <class It> spn_set_base(const It& _begin, const It& _end)
	: cmp(), _size(0) { extend(_begin, _end); }
	
	class iterator;
	iterator begin ();
	iterator end   ();
	iterator get   (size_t);
	
	size_t size             ()                     const noexcept ;
	bool   empty            ()                     const noexcept ;
	void   reserve          (size_t)                              ;
	void   clear            ()                     noexcept       ;
	void   shrink_to_fit    ()                     noexcept       ;
	template <class It>
	void   extend           (const It&, const It&)                ;
	template <class It>
	void   from_sorted      (const It&, const It&)                ;
	bool   insert           (const T&)                            ;
	bool   erase            (const T&)                            ;
	void   erase            (const iterator&)                     ;
	T      kth              (size_t)                              ;
	T      operator[]       (size_t)                              ;
	T      back             ()                     const          ;
	size_t lower_bound      (const T&)                            ;
	size_t upper_bound      (const T&)                            ;
	size_t count            (const T&)                            ;
	bool   contains         (const T&)                            ;
	T      precursor        (const T&)                            ;
	T      successor        (const T&)                            ;
	T      strict_precursor (const T&)                            ;
	T      strict_successor (const T&)                            ;
	void   swap             (spn_set_base&)                       ;
	void   join             (spn_set_base& other, bool keep_source=false);
	bool   operator==       (const spn_set_base&) const           ;
	bool   operator!=       (const spn_set_base&) const           ;
};

// ==================== iterator ====================

template <class T, class Cmp, bool Unique>
class spn_set_base<T, Cmp, Unique>::iterator {
private:
	spn_set_base<T, Cmp, Unique> *set;
	size_t                        pos, idx;
	iterator() : set(nullptr), pos(-1), idx(-1) {}
	iterator(spn_set_base<T, Cmp, Unique> *_set, size_t _pos, size_t _idx)
	: set(_set), pos(_pos), idx(_idx) {}
	friend class spn_set_base;
public:
	using value_type        = T;
	using difference_type   = std::ptrdiff_t;
	using pointer           = const T*;
	using reference         = const T&;
	using iterator_category = std::bidirectional_iterator_tag;
	
	iterator(const iterator& other) = default;
	iterator& operator=(const iterator& other) = default;
	
	operator size_t () { return set->loc(pos, idx); }
	
	const T& operator*  () const { return set->lists[pos][idx]; }
	const T* operator-> () const { return &set->lists[pos][idx]; }
	
	iterator& operator++ () {
		if (pos >= set->lists.size()) return *this;       // 已在 end,不前进
		if (++idx >= set->lists[pos].size()) {
			pos++;
			idx = 0;
		}
		return *this;
	}
	iterator& operator-- () {
		if (pos == 0 && idx == 0) return *this;           // 已在 begin,不后退
		if (pos >= set->lists.size()) {                   // 从 end() 后退
			pos = set->lists.size() - 1;
			idx = set->lists[pos].size() - 1;
		} else if (idx == 0) {
			pos--;
			idx = set->lists[pos].size() - 1;
		} else {
			idx--;
		}
		return *this;
	}
	iterator operator++ (int) {
		iterator temp = *this;
		++*this;
		return temp;
	}
	iterator operator-- (int) {
		iterator temp = *this;
		--*this;
		return temp;
	}
	bool operator== (const iterator& other) const {
		return set == other.set && pos == other.pos && idx == other.idx;
	}
	bool operator!= (const iterator& other) const {
		return !(*this == other);
	}
};

// ==================== begin / end / get ====================

template <class T, class Cmp, bool Unique>
typename spn_set_base<T, Cmp, Unique>::iterator
spn_set_base<T, Cmp, Unique>::begin() {
	return iterator(this, 0, 0);
}
template <class T, class Cmp, bool Unique>
typename spn_set_base<T, Cmp, Unique>::iterator
spn_set_base<T, Cmp, Unique>::end() {
	return iterator(this, lists.size(), 0);
}
template <class T, class Cmp, bool Unique>
typename spn_set_base<T, Cmp, Unique>::iterator
spn_set_base<T, Cmp, Unique>::get(size_t idx) {
	if (idx >= _size) throw std::out_of_range("index out of range");
	const auto& [a, b] = pos(idx);
	return iterator(this, a, b);
}

// ==================== Fenwick tree ====================

template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::build() {
	size_t n = lists.size();
	index.assign(n, 0);
	for (size_t i = 1; i < n; i++) {
		index[i] += lists[i - 1].size();
		size_t x = i + (i & -i);
		if (x < n) index[x] += index[i];
	}
}
template <class T, class Cmp, bool Unique>
std::pair<size_t, size_t> spn_set_base<T, Cmp, Unique>::pos(size_t idx) {
	if (idx < lists[0].size()) return {0, idx};
	if (index.empty()) build();
	size_t n = index.size(), p = 0;
	for (size_t i = floor_log2(n); i != (size_t)-1; i--) {
		size_t x = p + (1 << i);
		if (x < n && idx >= index[x]) idx -= index[x], p = x;
	}
	return {p, idx};
}
template <class T, class Cmp, bool Unique>
size_t spn_set_base<T, Cmp, Unique>::loc(size_t pos, size_t idx) {
	if (pos == 0) return idx;
	if (index.empty()) build();
	while (pos > 0) idx += index[pos], pos &= pos - 1;
	return idx;
}

// ==================== 基本操作 ====================

template <class T, class Cmp, bool Unique>
size_t spn_set_base<T, Cmp, Unique>::size() const noexcept { return _size; }
template <class T, class Cmp, bool Unique>
bool spn_set_base<T, Cmp, Unique>::empty() const noexcept { return maxes.empty(); }
template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::clear() noexcept
{ _size = 0, lists.clear(), maxes.clear(), index.clear(); }
template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::shrink_to_fit() noexcept
{ lists.shrink_to_fit(), maxes.shrink_to_fit(), index.shrink_to_fit(); }

// [FIX #2] maxes.resize → maxes.reserve
template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::reserve(size_t len)
{ lists.reserve(len / _load + 1), maxes.reserve(len / _load + 1); }

// ==================== insert ====================

template <class T, class Cmp, bool Unique>
bool spn_set_base<T, Cmp, Unique>::insert(const T& val) {
	if (maxes.empty()) {
		lists.emplace_back(1, val), maxes.emplace_back(val), _size++;
		return true;
	}
	size_t pos = std::upper_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	auto equals = [this](const T& a, const T& b) {
		return !cmp(a, b) && !cmp(b, a);
	};
	if (pos == maxes.size()) {
		if (Unique && equals(val, maxes.back())) return false;
		pos--, lists[pos].emplace_back(val), maxes[pos] = val;
	} else {
		auto it = std::upper_bound(lists[pos].begin(), lists[pos].end(), val, cmp);
		if (Unique) {
			if (it != lists[pos].begin()) {
				if (equals(val, *std::prev(it))) return false;
			} else if (pos > 0) {
				if (equals(val, lists[pos - 1].back())) return false;
			}
		}
		lists[pos].insert(it, val);
	}
	_size++, split(pos);
	return true;
}

// ==================== split / merge ====================

template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::split(size_t pos) {
	if (lists[pos].size() > (_load << 1)) {
		std::vector<T> half(lists[pos].begin() + _load, lists[pos].end());
		lists[pos].erase(lists[pos].begin() + _load, lists[pos].end());
		maxes[pos] = lists[pos].back();
		lists.insert(lists.begin() + pos + 1, half);
		maxes.insert(maxes.begin() + pos + 1, half.back());
		index.clear();
	} else if (!index.empty()) {
		size_t n = index.size();
		for (size_t i = pos + 1; i < n; i += (i & -i)) index[i]++;
	}
}
template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::merge(size_t pos) {
	lists[pos - 1].insert(lists[pos - 1].end(), lists[pos].begin(), lists[pos].end());
	maxes[pos - 1] = lists[pos - 1].back();
	lists.erase(lists.begin() + pos), maxes.erase(maxes.begin() + pos), index.clear();
}

// ==================== extend / from_sorted ====================

template <class T, class Cmp, bool Unique> template <class It>
void spn_set_base<T, Cmp, Unique>::extend(const It& _begin, const It& _end) {
	ptrdiff_t len = std::distance(_begin, _end);
	if ((len << 2) < (ptrdiff_t)_size) {
		for (It it = _begin; it != _end; it++) insert(*it);
		return;
	}
	std::vector<T> a(_begin, _end);
	for (const std::vector<T>& vec : lists) a.insert(a.end(), vec.begin(), vec.end());
	std::sort(a.begin(), a.end(), cmp);
	if (Unique) {
		auto last = std::unique(a.begin(), a.end(),
								[this](const T& x, const T& y) { return !cmp(x, y) && !cmp(y, x); });
		a.erase(last, a.end());
	}
	clear(), _size = a.size();
	for (size_t i = 0; i < _size; i += _load) {
		lists.emplace_back(a.begin() + i, a.begin() + std::min(_size, i + _load));
		maxes.emplace_back(lists.back().back());
	}
}
template <class T, class Cmp, bool Unique> template <class It>
void spn_set_base<T, Cmp, Unique>::from_sorted(const It& _begin, const It& _end) {
	std::vector<T> a(_begin, _end);
	if (Unique) {
		auto last = std::unique(a.begin(), a.end(),
								[this](const T& x, const T& y) { return !cmp(x, y) && !cmp(y, x); });
		a.erase(last, a.end());
	}
	clear(), _size = a.size();
	for (size_t i = 0; i < _size; i += _load) {
		lists.emplace_back(a.begin() + i, a.begin() + std::min(_size, i + _load));
		maxes.emplace_back(lists.back().back());
	}
}

// ==================== erase ====================

template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::erase(size_t pos, size_t idx) {
	lists[pos].erase(lists[pos].begin() + idx), _size--;
	size_t len = lists[pos].size();
	if (len > (_load >> 1)) {
		maxes[pos] = lists[pos].back();
		if (!index.empty()) {
			size_t idx_n = index.size();
			for (size_t i = pos + 1; i < idx_n; i += (i & -i)) index[i]--;
		}
	} else if (lists.size() > 1) {
		if (pos == 0) pos++;
		merge(pos), split(pos - 1);
	} else if (len > 0) {
		maxes[pos] = lists[pos].back();
	} else {
		lists.erase(lists.begin() + pos), maxes.erase(maxes.begin() + pos), index.clear();
	}
}
template <class T, class Cmp, bool Unique>
bool spn_set_base<T, Cmp, Unique>::erase(const T& val) {
	if (maxes.empty()) return false;
	size_t pos = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) return false;
	size_t idx = std::lower_bound(lists[pos].begin(), lists[pos].end(), val, cmp) - lists[pos].begin();
	if (idx >= lists[pos].size() || cmp(lists[pos][idx], val) || cmp(val, lists[pos][idx])) return false;
	erase(pos, idx);
	return true;
}
template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::erase(const iterator& it) { erase(it.pos, it.idx); }

// ==================== kth / operator[] / back ====================

template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::kth(size_t k) {
	if (k >= _size) throw std::out_of_range("index out of range");
	const auto& [a, b] = pos(k);
	return lists[a][b];
}
template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::operator[](size_t k) { return kth(k); }
template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::back() const {
	if (maxes.empty()) throw std::out_of_range("index out of range");
	return maxes.back();
}

// ==================== lower_bound / upper_bound / count / contains ====================

template <class T, class Cmp, bool Unique>
size_t spn_set_base<T, Cmp, Unique>::lower_bound(const T& val) {
	if (maxes.empty()) return 0;
	size_t pos = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) return _size;
	return loc(pos, std::lower_bound(lists[pos].begin(), lists[pos].end(), val, cmp) - lists[pos].begin());
}
template <class T, class Cmp, bool Unique>
size_t spn_set_base<T, Cmp, Unique>::upper_bound(const T& val) {
	if (maxes.empty()) return 0;
	size_t pos = std::upper_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) return _size;
	return loc(pos, std::upper_bound(lists[pos].begin(), lists[pos].end(), val, cmp) - lists[pos].begin());
}
template <class T, class Cmp, bool Unique>
bool spn_set_base<T, Cmp, Unique>::contains(const T& val) {
	if (maxes.empty()) return false;
	size_t pos = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) return false;
	size_t idx = std::lower_bound(lists[pos].begin(), lists[pos].end(), val, cmp) - lists[pos].begin();
	if (idx >= lists[pos].size()) return false;
	return !cmp(val, lists[pos][idx]) && !cmp(lists[pos][idx], val);
}
template <class T, class Cmp, bool Unique>
size_t spn_set_base<T, Cmp, Unique>::count(const T& val) {
	if (Unique) return contains(val);
	if (maxes.empty()) return 0;
	size_t l = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (l == maxes.size()) return 0;
	size_t r = std::upper_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	size_t x = std::lower_bound(lists[l].begin(), lists[l].end(), val, cmp) - lists[l].begin();
	if (r == maxes.size()) return _size - loc(l, x);
	size_t y = std::upper_bound(lists[r].begin(), lists[r].end(), val, cmp) - lists[r].begin();
	if (l == r) return y - x;
	return loc(r, y) - loc(l, x);
}

// ==================== precursor / successor ====================

template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::precursor(const T& val) {
	if (maxes.empty()) throw std::out_of_range("precursor not found");
	size_t pos = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) return maxes.back();
	auto it = std::lower_bound(lists[pos].begin(), lists[pos].end(), val, cmp);
	if (it != lists[pos].end() && !cmp(val, *it) && !cmp(*it, val)) return *it;
	if (it != lists[pos].begin()) return *std::prev(it);
	if (pos == 0) throw std::out_of_range("precursor not found");
	return maxes[pos - 1];
}
template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::successor(const T& val) {
	if (maxes.empty()) throw std::out_of_range("successor not found");
	size_t pos = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) throw std::out_of_range("successor not found");
	auto it = std::lower_bound(lists[pos].begin(), lists[pos].end(), val, cmp);
	if (it != lists[pos].end()) return *it;
	if (pos + 1 == maxes.size()) throw std::out_of_range("successor not found");
	return lists[pos + 1][0];
}
template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::strict_precursor(const T& val) {
	if (maxes.empty()) throw std::out_of_range("precursor not found");
	if (cmp(maxes.back(), val)) return maxes.back();
	size_t pos = std::lower_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) throw std::out_of_range("precursor not found");
	auto it = std::lower_bound(lists[pos].begin(), lists[pos].end(), val, cmp);
	if (it != lists[pos].begin()) return *std::prev(it);
	if (pos == 0) throw std::out_of_range("precursor not found");
	return maxes[pos - 1];
}
template <class T, class Cmp, bool Unique>
T spn_set_base<T, Cmp, Unique>::strict_successor(const T& val) {
	if (maxes.empty()) throw std::out_of_range("successor not found");
	size_t pos = std::upper_bound(maxes.begin(), maxes.end(), val, cmp) - maxes.begin();
	if (pos == maxes.size()) throw std::out_of_range("successor not found");
	auto it = std::upper_bound(lists[pos].begin(), lists[pos].end(), val, cmp);
	if (it == lists[pos].end()) throw std::out_of_range("successor not found");
	return *it;
}

// ==================== swap / join ====================

template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::swap(spn_set_base& other) {
	std::swap(_size, other._size);
	lists.swap(other.lists), maxes.swap(other.maxes), index.swap(other.index);
}

template <class T, class Cmp, bool Unique>
void spn_set_base<T, Cmp, Unique>::join(spn_set_base& other, bool keep_source) {
	if (this == &other) return;
	if (other.empty()) return;
	
	if (empty()) {
		if (keep_source) {
			lists = other.lists;
			maxes = other.maxes;
			index = other.index;
			_size = other._size;
		} else {
			swap(other);
		}
		return;
	}
	
	bool disjoint_append = false;
	if (Unique) {
		if (cmp(maxes.back(), other.lists[0].front())) disjoint_append = true;
	} else {
		if (!cmp(other.lists[0].front(), maxes.back())) disjoint_append = true;
	}
	
	if (disjoint_append) {
		if (keep_source) {
			lists.reserve(lists.size() + other.lists.size());
			maxes.reserve(maxes.size() + other.maxes.size());
			for (const auto& vec : other.lists) {
				lists.push_back(vec);
				maxes.push_back(vec.back());
			}
		} else {
			for (auto& vec : other.lists) {
				lists.push_back(std::move(vec));
				maxes.push_back(lists.back().back());
			}
		}
		_size += other._size;
		index.clear();
		if (!keep_source) other.clear();
		return;
	}
	
	if (other._size * 8 < _size) {
		for (const auto& block : other.lists)
			for (const auto& val : block)
				insert(val);
		if (!keep_source) other.clear();
		return;
	}
	
	std::vector<T> flat_a;
	flat_a.reserve(_size);
	for (auto& vec : lists)
		flat_a.insert(flat_a.end(), std::make_move_iterator(vec.begin()),
					  std::make_move_iterator(vec.end()));
	
	std::vector<T> flat_b;
	flat_b.reserve(other._size);
	if (keep_source) {
		for (const auto& vec : other.lists)
			flat_b.insert(flat_b.end(), vec.begin(), vec.end());
	} else {
		for (auto& vec : other.lists)
			flat_b.insert(flat_b.end(), std::make_move_iterator(vec.begin()),
						  std::make_move_iterator(vec.end()));
	}
	
	std::vector<T> merged;
	merged.reserve(_size + other._size);
	std::merge(std::make_move_iterator(flat_a.begin()), std::make_move_iterator(flat_a.end()),
			   std::make_move_iterator(flat_b.begin()), std::make_move_iterator(flat_b.end()),
			   std::back_inserter(merged), cmp);
	
	if (Unique) {
		auto last = std::unique(merged.begin(), merged.end(),
								[this](const T& a, const T& b) { return !cmp(a, b) && !cmp(b, a); });
		merged.erase(last, merged.end());
	}
	
	from_sorted(merged.begin(), merged.end());
	if (!keep_source) other.clear();
}

// ==================== operator== / operator!= ====================

template <class T, class Cmp, bool Unique>
bool spn_set_base<T, Cmp, Unique>::operator==(const spn_set_base& other) const {
	if (_size != other._size) return false;
	size_t pos1 = 0, idx1 = 0, pos2 = 0, idx2 = 0;
	while (pos1 < lists.size() && pos2 < other.lists.size()) {
		if (cmp(lists[pos1][idx1], other.lists[pos2][idx2]) ||
			cmp(other.lists[pos2][idx2], lists[pos1][idx1])) return false;
		idx1++, idx2++;
		if (idx1 >= lists[pos1].size()) pos1++, idx1 = 0;
		if (idx2 >= other.lists[pos2].size()) pos2++, idx2 = 0;
	}
	return true;
}
template <class T, class Cmp, bool Unique>
bool spn_set_base<T, Cmp, Unique>::operator!=(const spn_set_base& other) const {
	return !(*this == other);
}

// ==================== 类型别名 ====================

template <class T, class Cmp = std::less<T>>
using spn_set = spn_set_base<T, Cmp, true>;
template <class T, class Cmp = std::less<T>>
using spn_multiset = spn_set_base<T, Cmp, false>;

// ==================== ostream ====================

template<typename T>
std::ostream& operator<<(std::ostream& os, spn_set<T>& s) {
	os << "{ ";
	std::string sep;
	for (auto it = s.begin(); it != s.end(); ++it)
		os << sep << (*it), sep = ", ";
	return os << " }";
}
template<typename T>
std::ostream& operator<<(std::ostream& os, spn_multiset<T>& s) {
	os << "{ ";
	std::string sep;
	for (auto it = s.begin(); it != s.end(); ++it)
		os << sep << (*it), sep = ", ";
	return os << " }";
}

#endif //SPN_SET_H