跳到正文

个人记录

set维护连续段

Cap1taL约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

可以使用 std::function 传入回调

C++
class SegmentSet{
	class Element{
	public:
		int l,r;
		int val;
		bool operator < (const Element& _x)const{
			return l==_x.l?r<_x.r:l<_x.l;
		}
	};
	set<Element> st;
public:
	void clear(){
		st.clear();
		st.insert({1,1000000000,0});
	}
	void insert(int l,int r,int val,function<void(int,int,int,int)> call=[](int,int,int,int){}){
		while(1){
			auto it=st.lower_bound({l,l,0});
			if(it==st.end() || it->l>=r){
				if(it!=st.begin()){
					it--;
					if(it->r>l){
						if(it->r>r){
							call(l,r,it->val,val);
							int L=it->l,R=it->r,V=it->val;
							st.erase(it);
							st.insert({L,l,V});
							st.insert({r,R,V});
						}else{
							call(l,it->r,it->val,val);
							int L=it->l,V=it->val;
							st.erase(it);
							st.insert({L,l,V});
						}
					}
				}
				break;
			}
			if(it->r<=r){
				call(it->l,it->r,it->val,val);
				st.erase(it);
			}else{
				int R=it->r,V=it->val;
				call(it->l,r,it->val,val);
				st.erase(it);
				st.insert({r,R,V});
			}
		}
		st.insert({l,r,val});
	}
}sg;
原文