Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Segment Tree Basics

B433b981e15d8f2373df4363352434f9?s=47 halfrost
January 15, 2020

Segment Tree Basics

B433b981e15d8f2373df4363352434f9?s=128

halfrost

January 15, 2020
Tweet

Transcript

  1. Segment Tree 基础篇

  2. Range Minimum/Maximum Query •需求:在饿了么的⼀个⽤户的历史订单中,找出该⽤户指定⼀段 时间内单笔订单最贵/最便宜的订单 One problem •O(n), when query

    K —> ∞ times ?
  3. Range Minimum/Maximum Query •需求:在饿了么的⼀个⽤户的历史订单中,求出找出该⽤户指定 ⼀段时间内累积消费总⾦额 Another problem •O(n), when query

    K —> ∞ times ? •prefixSum, time O(n), query O(1)
  4. Range Minimum/Maximum Query •需求:在 12306 ⽹站上,统计⼀条线路上任意指定两个站点之间 的可售出的票数总和 One more thing

    •O(n), when query K —> ∞ times ? •prefixSum, time O(n), update O(n), query O(1)
  5. How to ? Range Minimum/Maximum Query 5 O(log n) or

    O(1) ?
  6. Presentation agenda 6 What How to use Leetcode example What

    is segment tree 2 3 1 How Example
  7. Define Segment Tree 7 1. ❌ Complete Binary Tree 2.

    ∈ Balanced Binary Tree 3. As Full binary tree
  8. How many node Segment Tree 8 0-level : 1 1-level

    : 2 2-level : 4 3-level : 8 4-level : 16 (n-1)—level :2^(n-1) n-level:2^n Σ 0-(n-1) level:Σ = 2^n - 1 ≈ n-level => 2n Mathematical Induction:Σ = 4n (n = 2^k or n = 2^k + 1)
  9. How many node Segment Tree 9 •When n≥3, [1,n] segment

    split [1,n] into 2*⌊log (n-1)⌋ sub- Interval •4n ≥ 2*⌊log (n-1)⌋ <= 2n ≥ log (n-1) <= 4^n ≥ n-1
  10. How to create Segment Tree 10

  11. How to query Segment Tree 11 ❗

  12. How to update Segment Tree 12 ❗

  13. How to update Segment Tree 13 •Update [2,3] ? •❌

    O(n)
  14. How to update Segment Tree 14 •Update [2,3] ? •✅O(log

    n)
  15. How to update Segment Tree 15

  16. How to query Segment Tree 16 •push_down

  17. How to update Segment Tree 17 •push_down + push_up

  18. How to low space Segment Tree 18 •Leetcode 715

  19. Compared ST VS Array 19 20% 80% 60% 40% 2585

    785 Update: Array O(n) | Segment Tree O(log n) Query: Array O(n) | Segment Tree O(log n)
  20. Segment Tree 20 Example

  21. Segment Tree 21 Example

  22. Segment Tree 22 Example

  23. Boyer-Moore Majority Vote Algorithm 23 Example

  24. Segment Tree 24 Example

  25. Segment Tree 25 Example •judge threshold •count = map[1:[0 1

    4 5] 2:[2 3]] •eg: 1 in [0,5] count , twice binary search, find [lowerBound, upperBound) •(upperBound - lowerBound) ≥ threshold
  26. Segment Tree 26 •Leetcode 327. Count of Range Sum •Leetcode

    715. Range Module •Leetcode 699. Falling Squares & 732. My Calendar III •Leetcode 850. Rectangle Area II •Leetcode 218. The Skyline Problem Exercise
  27. Advance 27 15% 35% 50% •One point update (update: min/change,

    query: sum/min) •Interval update (update: min/change, query: sum/hash) •Discretization •Interval merge •Scan line •Binary Index Tree