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 71 72
| class SegTreeNode(): #python3中所有类默认都是新式类 def __init__(self): #类似构造函数,类方法必须包含参数self self.value=0 self.lazytag=0
Data=[0 for i in range(0,100010)]
class SegTree(): def __init__(self): self.SegTree=[SegTreeNode() for i in range(0,400010)]
def Build_SegTree(self,Root,L,R): if L==R: self.SegTree[Root].value=Data[L] return mid=(L+R)>>1 self.Build_SegTree(Root<<1,L,mid) self.Build_SegTree(Root<<1|1,mid+1,R) self.SegTree[Root].value=self.SegTree[Root<<1].value+self.SegTree[Root<<1|1].value return
def Push_Down(self,Root,L,R): if self.SegTree[Root].lazytag==0: return Add=self.SegTree[Root].lazytag self.SegTree[Root].lazytag=0 mid=(L+R)>>1 self.SegTree[Root<<1].value+=(mid-L+1)*Add self.SegTree[Root<<1|1].value+=(R-mid)*Add self.SegTree[Root<<1].lazytag+=Add self.SegTree[Root<<1|1].lazytag+=Add return
def Update(self,Root,L,R,QL,QR,Add): if R<QL or QR<L: return if QL<=L and R<=QR: self.SegTree[Root].value+=(R-L+1)*Add self.SegTree[Root].lazytag+=Add return mid=(L+R)>>1 self.Push_Down(Root,L,R) self.Update(Root<<1,L,mid,QL,QR,Add) self.Update(Root<<1|1,mid+1,R,QL,QR,Add) self.SegTree[Root].value=self.SegTree[Root<<1].value+self.SegTree[Root<<1|1].value return
def Query(self,Root,L,R,QL,QR): if R<QL or QR<L: return 0 if QL<=L and R<=QR: return self.SegTree[Root].value mid=(L+R)>>1 self.Push_Down(Root,L,R) return self.Query(Root<<1,L,mid,QL,QR)+self.Query(Root<<1|1,mid+1,R,QL,QR)
Tree=SegTree() N,M=map(int,input().split()) a=input().split() #初始值
for i in range(1,N+1): Data[i]=int(a[i-1])
Tree.Build_SegTree(1,1,N)
while M: opt,L,R=map(int,input().split()) if opt==1: Tree.Update(1,1,N,L,R,int(a[3])) else: print(str(Tree.Query(1,1,N,L,R))) M-=1
|