Python实现线段树

简介: 代码如下
class SegmentTreeDynamic:
    class Node:
        left, right = None, None
        val, add = 0, 0
        # def __init__(self, left, right, val, add):
        #     self.left = left
        #     self.right = right
        #     self.val = val
        #     self.add = add
        def __init__(self):
            pass
    N = int(1e9)
    root = Node()
    def update(self, node, start, end, l, r, val):
        if l <= start and end <= r:
            node.val += ((end - start) + 1) * val
            node.add = val
            return
        mid = (start + end) >> 1
        self.pushDown(node, mid - start + 1, end - mid)
        if l <= mid: self.update(node.left, start, mid, l, r, val)
        if r > mid: self.update(node.right, mid + 1, end, l, r, val)
        self.pushup(node)
    def pushup(self, node):
        node.val = node.left.val + node.right.val
    def pushDown(self, node, leftNum, rightNum):
        if node.left is None: node.left = self.Node()
        if node.right is None: node.right = self.Node()
        if node.add == 0: return
        node.left.val = node.add * leftNum
        node.right.val = node.add * rightNum
        node.add = 0
    def query(self, node, start, end, l, r):
        if l <= start and end <= r: return node.val
        mid, ans = (start + end) >> 1, 0
        self.pushDown(node, mid - start + 1, end - mid)
        if l <= mid: ans += self.query(node.left, start, mid, l, r)
        if r > mid: ans += self.query(node, mid + 1, end, l, r)
        return ans
目录
相关文章
|
5月前
|
算法 索引 Python
Python高级数据结构——线段树(Segment Tree)
Python高级数据结构——线段树(Segment Tree)
240 2
|
Python
Python实现因子分析(附案例实战)
Python实现因子分析(附案例实战)
1472 0
Python实现因子分析(附案例实战)
Python print() 打印两个 list ,实现中间换行
Python print() 打印两个 list ,实现中间换行
|
算法 大数据 Python
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
149 2
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
|
机器学习/深度学习 算法 Python
利用python实现逻辑回归(以鸢尾花数据为例)
利用python实现逻辑回归(以鸢尾花数据为例)
266 0
利用python实现逻辑回归(以鸢尾花数据为例)
|
存储 数据安全/隐私保护 计算机视觉
python 实现pacs功能 推送下拉影像
python 实现dcmtk关联pacs功能 推送下拉影像
267 0
python 实现pacs功能 推送下拉影像
|
前端开发 Python
Leecode加法题目3个 每日练习 Python实现
Leecode加法题目3个 每日练习 Python实现
107 0
Leecode加法题目3个 每日练习 Python实现
|
iOS开发 Python
Python实现微信消息连续发送
Python实现微信消息连续发送
Python实现微信消息连续发送
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
|
机器学习/深度学习 算法 数据可视化
Python实现聚类分析和数据降维
Python实现聚类分析和数据降维
865 0
Python实现聚类分析和数据降维
下一篇
无影云桌面