classCountIntervals { public: CountIntervals() {} voidadd(int left, int right){ auto it2 = split(right + 1); auto it1 = it2; while (it1 != st.begin() && prev(it1)->second <= right && prev(it1)->second >= left) { --it1; sz -= it1->second - it1->first + 1; if (it1->first < left) { left = it1->first; } } st.erase(it1, it2); st.emplace(left, right); sz += right - left + 1; } intcount(){ return sz; }
private: set<pair<int, int>>::iterator split(int x){ auto it = st.upper_bound({x, -1}); if (it == st.begin()) return it; if (prev(it)->first == x || prev(it)->second < x) return it; --it; int l = it->first, r = it->second; st.erase(it); st.emplace(l, x - 1); return st.emplace(x, r).first; }