线段树实现。很多细节值得品味 都在注释里面了

class SegTree:
def __init__(self,N,query_fn,update_fn):
self.tree=[0]*(2*N+2) # 最后一个节点有可能无用 ,但是确保树是完全的
self.lazy=[0]*(N+1)
self.N=N self.h=0
while ((1<<self.h) < N ):
self.h=self.h+1 self.query_fn=query_fn
self.update_fn=update_fn #这里实现只有单个节点的更改,对于整个节点来说以上的节点没有杯更新到 所以要使用 pull 做进一步的更改
def _apply(self,x,val):
self.tree[x] = self.update_fn(val,self.tree[x]) if(x<self.N):
self.lazy[x]=self.update_fn(self.lazy[x] , self.tree[x]) '''
pull
从叶部到根部 ,用于更新后的维护 push
从根部到叶部 ,查询前的维护 ''' def pull(self,x): while x>1 : # 先while 再除 保证了 (x==1 仍然会执行&&第一次执行的时候不是叶子节点)
x = x // 2
self.tree[x] = self.query_fn(self.tree[x*2+1],self.tree[x*2 ] ) #针对区间之间的信息 是 query_fn self.tree[x] = self.update_fn(self.tree[x],self.lazy[x]) def push(self,x):
for i in range(self.h,0,-1):
y = x >> i
if(self.lazy[ y ]): #巧妙的使用了 lazy 前空出无用的 lazy[0]
self._apply(y*2, self.lazy[y]) #_apply 代码的复用 (修改值 并且置 lazy )
self._apply(y*2+1, self.lazy[y])
self.lazy[y]=0 def update(self,left,right,val):
#print("update "+str(left )+" "+str(right )+" "+str(val))
left =left +self.N
right=right+self.N init_left = left
init_right = right
while(left<=right): #追溯最邻近父节点的写法 if( left & 1 ):
self._apply(left , val )
left = left +1 if((right & 1) ==0):
self._apply(right, val)
right = right -1 left = left // 2
right = right // 2 #以上只更新到左右节点的最邻近父节点 所以需要进行pull 更新上面的所有节点
self.pull( init_left )
self.pull( init_right ) def query(self,left,right):
#print("query "+str(left )+" "+str(right ))
left = left +self.N
right = right + self.N
self.push( left )
self.push( right ) ans = 0
while ( left <= right ):#追溯最邻近父节点
#print("left "+str(left)+" right"+str(right))
if(left & 1): ans= self.query_fn(ans , self.tree[left] )
left = left + 1 #这个+1 是为了对称 没有实际意义? if((right & 1) ==0 ):
#print(right)
ans = self.query_fn(ans , self.tree[right ])
right = right -1 left = left // 2
right = right // 2
return ans class Solution:
def fallingSquares(self, positions):
"""
:type positions: List[List[int]]
:rtype: List[int]
"""
position = [i[0] for i in positions]
position . extend([i[0]+i[1]-1 for i in positions]) position=sorted(set(position)) pos2idx ={pos:i+1 for i,pos in enumerate(position)} N=len(pos2idx) #print("N is "+str(N))
segtree=SegTree(N,max,max) best = -1
ans_list = []
#print(pos2idx)
for block in positions:
l,r=pos2idx[block[0]],pos2idx[block[0]+block[1]-1] height = segtree.query(l,r) + block[1]
#print("query height"+str(height-block[1])+" blcok size:"+str(block[1])) segtree.update(l,r,height) best=max(best,height) ans_list.append(best) return ans_list

leetcode 699. Falling Squares 线段树的实现的更多相关文章

  1. 【leetcode】699. Falling Squares

    题目如下: On an infinite number line (x-axis), we drop given squares in the order they are given. The i- ...

  2. 699. Falling Squares

    On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th squ ...

  3. 【LeetCode】线段树 segment-tree(共9题)+ 树状数组 binary-indexed-tree(共5题)

    第一部分---线段树:https://leetcode.com/tag/segment-tree/ [218]The Skyline Problem [307]Range Sum Query - Mu ...

  4. HDU 1264 Counting Squares (线段树-扫描线-矩形面积并)

    版权声明:欢迎关注我的博客.本文为博主[炒饭君]原创文章,未经博主同意不得转载 https://blog.csdn.net/a1061747415/article/details/25471349 P ...

  5. C#LeetCode刷题-线段树

    线段树篇 # 题名 刷题 通过率 难度 218 天际线问题   32.7% 困难 307 区域和检索 - 数组可修改   42.3% 中等 315 计算右侧小于当前元素的个数   31.9% 困难 4 ...

  6. Sum of Squares of the Occurrence Counts解题报告(后缀自动机+LinkCutTree+线段树思想)

    题目描述 给定字符串\(S(|S|\le10^5)\),对其每个前缀求出如下的统计量: 对该字符串中的所有子串,统计其出现的次数,求其平方和. Sample Input: aaa Sample Out ...

  7. 【Codeforces720D】Slalom 线段树 + 扫描线 (优化DP)

    D. Slalom time limit per test:2 seconds memory limit per test:256 megabytes input:standard input out ...

  8. poj 1195:Mobile phones(二维线段树,矩阵求和)

    Mobile phones Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 14391   Accepted: 6685 De ...

  9. Codeforces Round #337 (Div. 2) D. Vika and Segments 线段树 矩阵面积并

    D. Vika and Segments     Vika has an infinite sheet of squared paper. Initially all squares are whit ...

随机推荐

  1. Postman提取返回值

    json响应结果 Postman是做接口测试的,但是很多接口并不是直接就能测试的,需要一些预处理.比如登录的时候,需要传递一个token.如果是网页测试,一般打开登录页面的时候就会自动生成一个toke ...

  2. 深夜Python - 第2夜 - 爬行

    深夜Python - 第2夜 - 爬行 我曾经幻想自己是一只蜗牛,有自己的一只小壳,不怕风,不怕雨,浪荡江湖,游历四方……夜猫兄一如既往地打断了我不切实际的幻想:“浪荡?游历?等你退休了都爬不出家门口 ...

  3. POJ 1127 /// 判断线段与线段是否相交

    题目大意: 给定n条线段 接下来n行是端点信息 接下来询问 a b 是否相交 若a与c相交 b与c相交 ,那么a与b就是相交的 先判断任两条线段是否相交 再用folyd #include <cs ...

  4. 锋利的Jquery(p的onclick()事件)

    1.一个p元素的点击事件 <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="serve ...

  5. wordpress jwt-auth 多语言 jwt_auth_bad_iss的解决方法

    因为目前处理的 wordpress 网站使用了,使用 qtranslate-x 多语言插件 JWT Authentication for WP REST API 插件 rest api 登录 调用wp ...

  6. Python3基础笔记_字典

    # Python3 字典 dict = {'} # 1.访问字典里的值 ,字典中没有key会报错 # 2.修改字典 print("修改之前:", dict['Beth']) dic ...

  7. 基于 RocketMQ 的同城双活架构在美菜网的挑战与实践

    本文整理自李样兵在北京站 RocketMQ meetup分享美菜网使用 RocketMQ 过程中的一些心得和经验,偏重于实践. 嘉宾李样兵,现就职于美菜网基础服务平台组,负责 MQ ,配置中心和任务调 ...

  8. csp-s模拟测试56Merchant, Equation,Rectangle题解

    题面:https://www.cnblogs.com/Juve/articles/11619002.html merchant: 二分答案,贪心选前m大的 但是用sort复杂度不优,会T掉 我们只是找 ...

  9. light oj 1231 dp 多重背包

    #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> ...

  10. Java-Shiro:目录

    ylbtech-Java-Shiro:目录 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   作者:ylbtech出处:http://yl ...