Simple C++ and set
\nclass CountIntervals {\npublic:\n    set<pair<int,int>> s;\n    int sum = 0;\n    CountIntervals() {\n        sum = 0;\n    }\n    void add(int left, int righ
```\nclass CountIntervals {\npublic:\n    set<pair<int,int>> s;\n    int sum = 0;\n    CountIntervals() {\n        sum = 0;\n    }\n    void add(int left, int right)  {\n        auto iter = s.upper_bound({left, INT_MAX});\n        if (iter != s.begin())\n            iter--;\n        if (iter != s.end() && iter->second < left)\n            iter++;\n        while (iter != s.end() && iter->first <= right) {\n            left = min(left, iter->first);\n            right = max(right, iter->second);\n            sum -= (iter->second - iter->first + 1);\n            iter = s.erase(iter);\n        }\n        s.insert({left, right});\n        sum += (right - left + 1);\n    }\n    int count()  {\n        return sum;\n    }\n};\n```
[]