[C++] merging intervals using set
\nusing pii = pair<int,int>;\nconst int inf = 1e9+7;\n\nclass CountIntervals {\npublic:\n  set<pii> s;\n  int cnt = 0 ;\n  CountIntervals() {\n    // Give some 
```\nusing pii = pair<int,int>;\nconst int inf = 1e9+7;\n\nclass CountIntervals {\npublic:\n  set<pii> s;\n  int cnt = 0 ;\n  CountIntervals() {\n    // Give some boundary for safety. \n    s.insert({-1,-1});   \n    s.insert({inf,inf}); \n  }\n\n  // Note that each interval inserted by a single call of add(int left, int right) can be removed at most once. \n  // So the overall complexity is O(nlogn).\n  void add(int left, int right) {\n    auto it = s.lower_bound({left,0});  // look for an interval with smallest l s.t. left <= l\n    int l,r;  // the left end and the right end of to-be-inserted interval {l,r}\n    l = left; \n    r = right;\n    if (it!=s.begin()) { // if there is an interval left side of it\n      auto temp = prev(it);\n      if ((*temp).second >= left) { // check if the cur.r >= left \n        l = (*temp).first;          // l should be updated \n        it = temp;\n      }\n    }\n    while (it != s.end()) {  // traverse through the set of intervals\n      if ((*it).second <= right) {  // the entire interval is included in [left,right]\n        auto [ll,rr] = *it;\n        cnt -= rr-ll+1;             // update cnt\n        auto temp = next(it);\n        s.erase(it);                // remove current interval represented by it\n        it = temp;\n      }  \n      else {                         // the entire interval is not included in [left,right]\n        if ((*it).first > right) {   // current interval represented by it does not overlap with to-be-inserted interval {l,r}\n          break;\n        }\n        else {                       // current interval represented by it overlaps with to-be-inserted interval, so we update r\n          r = ((*it).second);\n          auto [ll,rr] = *it;\n          cnt -= rr-ll+1;           // update cnt\n          s.erase(it);              // remove current interval represented by it\n          break;\n        }\n      }\n    }\n    s.insert({l,r});          // finally insert what we have prepared so far.\n    cnt += r-l+1;             // update cnt\n  }\n\n  int count() {\n      return cnt;\n  }\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 ```\n \n
['C', 'Ordered Set']