Rust Solution Using BTreeMap
~~~\nuse std::collections::BTreeMap;\nstruct CountIntervals {\n    cnt: i32,\n    mp: BTreeMap\n}\n\n\n/* \n * &self means the method takes an immutable referen
~~~\nuse std::collections::BTreeMap;\nstruct CountIntervals {\n    cnt: i32,\n    mp: BTreeMap<i32, i32>\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl CountIntervals {\n\n    fn new() -> Self {\n        let mp: BTreeMap<i32, i32> = BTreeMap::new(); \n        Self { cnt: 0, mp }\n    }\n    \n    fn add(&mut self, left: i32, right: i32) {\n        let (mut left, mut right) = (left, right);\n       \n        self.cnt += right - left + 1;\n        if self.mp.is_empty() {\n            self.mp.insert(left, right);\n            return\n        }\n        \n        let (a, _) = self.mp.iter().next().unwrap();\n        let (_, b) = self.mp.iter().rev().next().unwrap();\n        if a - 1 > right || b + 1 < left {\n            self.mp.insert(left, right);\n            return\n        }\n        \n\t\t// left end joining\n        if let Some((&key, &value)) = self.mp.range(..left + 1).rev().next() {\n            if value + 1 >= left {\n                if value > right { self.cnt -= right - left + 1; }\n                else { self.cnt -= value + 1  - left; }\n                left = key;\n                right = right.max(value);\n            }\n        }\n        \n\t\t// removing containing intervals\n        let mut done = false;\n        while done == false {\n            done = true;\n            if let Some((&key, &value)) = self.mp.range(left + 1..).next() {\n                if value > right { break; }\n                self.cnt -= value - key + 1;\n                self.mp.remove(&key);\n                done = false;\n            }\n        }\n        \n\t\t// right end joining\n        if let Some((&key, &value)) = self.mp.range(left + 1..).next() {\n            if right + 1 >= key {\n                self.cnt -= right + 1 - key;\n                right = value;\n                self.mp.remove(&key);\n            }\n        }\n        \n        self.mp.insert(left, right);\n    }\n    \n    fn count(&self) -> i32 {\n        self.cnt\n    }\n}\n~~~
['Rust']