微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

leetcode2276 统计区间中的整数数目

思路:

动态开点线段树,这里维护了区间和和区间赋值。

实现:

 1 class SegmentTree {
 2 public:
 3     int N = (int)1e9;
 4     class Node {
 5     public:
 6         // ls 和 rs 分别代表当前区间的左右子节点
 7         Node*ls=nullptr, *rs=nullptr;
 8         // val 代表当前区间的最大高度,add 为懒标记
 9         int val=0, add=0;
10         Node(){}
11     };
12     Node*root = nullptr;
13     SegmentTree(int n){
14         root=new Node();
15         N=n;
16     }
17     void update(int l,int r,int v){
18         _update(root,0,N,l,r,v);
19     }
20     void _update(Node*node, int lc, int rc, int l, int r, int v) {
21         if (l <= lc && rc <= r) {
22             node->add = v;
23             node->val = v*(rc-lc+1);
24             return ;
25         }
26         pushdown(node,lc,rc);
27         int mid = lc + rc >> 1;
28         if (l <= mid) _update(node->ls, lc, mid, l, r, v);
29         if (r > mid) _update(node->rs, mid + 1, rc, l, r, v);
30         pushup(node);
31     }
32     int query(int l,int r){
33         return _query(root,0,N,l,r);
34     }
35     int _query(Node*node, int lc, int rc, int l, int r) {
36         if (l <= lc && rc <= r) return node->val;
37         pushdown(node,lc,rc);
38         int mid = lc + rc >> 1, ans = 0;
39         if (l <= mid) ans = _query(node->ls, lc, mid, l, r);
40         if (r > mid) ans += _query(node->rs, mid + 1, rc, l, r);
41         return ans;
42     }
43     void pushdown(Node*node,int lc,int rc) {
44         if (node->ls == nullptr) node->ls = new Node();
45         if (node->rs == nullptr) node->rs = new Node();
46         if (node->add == 0) return ;
47         int mid=lc+rc>>1;
48         node->ls->add = node->add; node->rs->add = node->add;
49         node->ls->val = node->add*(mid-lc+1); node->rs->val = node->add*(rc-mid);
50         node->add = 0;
51     }
52     void pushup(Node*node) {
53         node->val = node->ls->val + node->rs->val;
54     }
55 
56 };
57 class CountIntervals {
58 public:
59     SegmentTree*st=NULL;
60     CountIntervals() {
61         st=new SegmentTree(1e9);
62 
63     }
64     
65     void add(int left, int right) {
66         st->update(left,right,1);
67 
68 
69     }
70     
71     int count() {
72         return st->query(0,1e9);
73 
74     }
75 };
76 
77 /**
78  * Your CountIntervals object will be instantiated and called as such:
79  * CountIntervals* obj = new CountIntervals();
80  * obj->add(left,right);
81  * int param_2 = obj->count();
82  */

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐