1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| import sys input = sys.stdin.readline
class tnode: def __init__(self): self.min = 0 self.lazy = 0 self.l = 0 self.r = 0
class SegmentTree: def __init__(self, n:int) -> None: self.t = [tnode() for _ in range(4 * (n+1))]
def pushdown(self, root:int) -> None: """懒标记下传合并, 根据题目要求设计""" if self.t[root].lazy != 0: self.t[root].min += self.t[root].lazy if self.t[root].l != self.t[root].r: ch = root << 1 self.t[ch].lazy += self.t[root].lazy self.t[ch+1].lazy += self.t[root].lazy self.t[root].lazy = 0
def update(self, root:int) -> None: """ 区间合并,根据维护的数据变动""" ch = root << 1 self.pushdown(ch) self.pushdown(ch+1) self.t[root].min = min(self.t[ch].min, self.t[ch+1].min)
def build(self, root:int, l:int, r:int, ls:list) -> None: """递归建树""" self.t[root].l = l self.t[root].r = r self.t[root].lazy = 0 if l != r: mid = (l+r)>>1 ch = root<<1 self.build(ch, l, mid, ls) self.build(ch+1, mid+1, r, ls) self.update(root) else: self.t[root].min = ls[l]
def change(self, root:int, l:int, r:int, delta:int) -> None: """ 作用: 区间修改 """ self.pushdown(root) if l == self.t[root].l and r == self.t[root].r: self.t[root].lazy += delta return mid = (self.t[root].l+self.t[root].r)>>1 ch = root<<1 if r <= mid: self.change(ch,l,r,delta) elif l > mid: self.change(ch+1,l,r,delta) else: self.change(ch,l,mid,delta) self.change(ch+1,mid+1,r,delta) self.update(root)
def query_min(self, root:int, l:int, r:int) -> int: self.pushdown(root) if self.t[root].l == l and self.t[root].r == r: return self.t[root].min mid = (self.t[root].l+self.t[root].r) >> 1 ch = root<<1 if r <= mid: return self.query_min(ch,l,r) elif l > mid: return self.query_min(ch+1,l,r) else: return min(self.query_min(ch,l,mid),self.query_min(ch+1,mid+1,r))
|