ACwing802-离散化-python-(数组数组+离散化)

比较难理解的一道题。我们首先对所有要进行添加操作的坐标进行离散化,用树状数组保存。当我们查询的时候,找到左右侧的端点,再利用树状数组求和即可。
AC代码

global a,lth
global tree
def low_bound(l,r,val):
    while l<=r:
        mid=l+r>>1
        if val<=a[mid]:
            r=mid-1
        else:
            l=mid+1
    return l
def lowbit(x):
    return x&(-x)
def add(x,val):
    while x<=lth:
        tree[x]+=val
        x+=lowbit(x)
def query(x):
    ans=0
    while x:
        ans+=tree[x]
        x-=lowbit(x)
    return ans
n,m=map(int,input().split())
op=[0]*n

dot=set()
for i in range(n):
    x,c=map(int,input().split())
    op[i]=[x,c]
    dot.add(x)
a=list(dot)
a.sort()
a.insert(0,float("-inf"))
lth=len(a)-1

tree=[0]*(lth+1)
for i in range(n):
    x,c=op[i][0],op[i][1]
    index=low_bound(0,lth,x)
    add(index,c)

for i in range(m):
    l,r=map(int,input().split())
    lindex=low_bound(0,lth,l)
    
    ans1=query(lindex-1)

    rindex=low_bound(0,lth,r)
    if rindex<=lth and a[rindex]==r:
        ans2=query(rindex)
    else:
        ans2=query(rindex-1)
    print(ans2-ans1)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值