Count Integers in Intervals
\n# Code\ncpp []\nclass CountIntervals {\npublic:\n    set<pair<int, int>> st;\n    int cnt;\n    CountIntervals() { cnt = 0; }\n\n    void add(int left, int ri
\n# Code\n```cpp []\nclass CountIntervals {\npublic:\n    set<pair<int, int>> st;\n    int cnt;\n    CountIntervals() { cnt = 0; }\n\n    void add(int left, int right) {\n        pair<int, int> newRange = {left, right};\n        auto it = st.lower_bound(newRange);\n\n        if (it != st.begin()) {\n            auto prev = it;\n            --prev;\n            if (prev->second >= left) {\n                it = prev;\n            }\n        }\n\n        vector<pair<int, int>> toRemove;\n        while (it != st.end() && it->first <= right) {\n            newRange.first = min(newRange.first, it->first);\n            newRange.second = max(newRange.second, it->second);\n\n            cnt -= (it->second - it->first + 1);\n\n            toRemove.push_back(*it);\n            ++it;\n        }\n\n        for (auto& rem : toRemove) {\n            st.erase(rem);\n        }\n\n        st.insert(newRange);\n        cnt += (newRange.second - newRange.first + 1);\n    }\n\n    int count() { return cnt; }\n};\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals* obj = new CountIntervals();\n * obj->add(left,right);\n * int param_2 = obj->count();\n */\n```
['C++']