python线段树

class Node:
    def __init__(this,l,r,vMax,vSum):
        this.l=l
        this.r=r
        this.vMax=vMax
        this.vSum=vSum
        this.fSum=0
        this.fMax=0
    def __init__(this):
        pass
class SegTree:
    def __init__(this,n,arr):
        this.tree=[Node() for i in range(4*n+1)]
        this.arr=list(arr)
    
    def build(this,l,r,k):
        this.tree[k].l=l
        this.tree[k].r=r
        if l==r:
            this.tree[k].vMax=this.arr[l-1]
            this.tree[k].vSum=this.arr[l-1]
            return

        m=(l+r)//2
        this.build(l,m,k*2)
        this.build(m+1,r,k*2+1)
        this.tree[k].vSum=this.tree[k*2].vSum+this.tree[k*2+1].vSum
        this.tree[k].vMax=max(this.tree[k*2].vMax,this.tree[k*2+1].vMax)

    def askMax(this,k,x,y):
        if (this.tree[k].l>=x and this.tree[k].r<=y):
            return this.tree[k].vMax
        
        res=0
        m=(this.tree[k].l+this.tree[k].r)//2
        if x<=m: 
            res=max(res,this.askMax(k*2,x,y))
        if y>m:
            res=max(res,this.askMax(k*2+1,x,y))
        return res
    
    def askSum(this,k,x,y):
        if (this.tree[k].l>=x and this.tree[k].r<=y):
            return this.tree[k].vSum
        
        res=0
        m=(this.tree[k].l+this.tree[k].r)//2
        if x<=m:
            res+=this.askSum(k*2,x,y)
        if y>m:
            res+=this.askSum(k*2+1,x,y)
        return res

    def modify(this,k,id,val,gap):
        this.tree[k].vSum+=gap
        #this.tree[k].vMax=max(this.tree[k].vMax,val)
        if this.tree[k].l==this.tree[k].r:
            this.arr[id-1]=val
            this.tree[k].vMax=val
            return
        m=(this.tree[k*2].l+this.tree[k*2+1].r)//2
        if id<=m:
            this.modify(k*2,id,val,gap)
        if id>m:
            this.modify(k*2+1,id,val,gap)
        this.tree[k].vMax=max(this.tree[k*2].vMax,this.tree[k*2+1].vMax)


n,m=list(map(int,input().split()))
arr=list(map(int,input().split()))
segTree=SegTree(n,arr)
segTree.build(1,n,1)

for i in range(m):
    p,x,y=list(map(int,input().split()))

    if p==1:
        segTree.modify(1,x,y,y-segTree.arr[x-1])
    elif p==2:
        print(segTree.askSum(1,x,y))
    else:
        print(segTree.askMax(1,x,y))```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值