segmenttree.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type node struct {
  6. l int
  7. r int
  8. left *node
  9. right *node
  10. val int
  11. inc int // Lazy
  12. }
  13. func (n node) mid() int {
  14. return n.l + (n.r-n.l)/2
  15. }
  16. var tree []node
  17. var tid int
  18. func newTree(n int) *node {
  19. tree = make([]node, 2*n)
  20. tid = 0
  21. root := &tree[0]
  22. root.buildTree(1, n)
  23. return root
  24. }
  25. func (root *node) buildTree(l, r int) {
  26. root.l = l
  27. root.r = r
  28. if l == r {
  29. return
  30. }
  31. tid++
  32. root.left = &tree[tid]
  33. tid++
  34. root.right = &tree[tid]
  35. m := l + (r-l)/2
  36. root.left.buildTree(l, m)
  37. root.right.buildTree(m+1, r)
  38. }
  39. func (root *node) update(l, r, val int) {
  40. if root.l == l && root.r == r {
  41. root.inc += val
  42. return
  43. }
  44. root.val += (r - l + 1) * val
  45. if r <= root.mid() {
  46. root.left.update(l, r, val)
  47. } else if root.mid()+1 <= l {
  48. root.right.update(l, r, val)
  49. } else {
  50. root.left.update(l, root.mid(), val)
  51. root.right.update(root.mid()+1, r, val)
  52. }
  53. }
  54. func (root *node) query(l, r int) int {
  55. if root.l == l && root.r == r {
  56. return root.val + (r-l+1)*root.inc
  57. }
  58. if root.inc != 0 {
  59. root.val += (root.r - root.l + 1) * root.inc // PushDown
  60. root.left.update(root.l, root.mid(), root.inc) // !!the RANGE is important
  61. root.right.update(root.mid()+1, root.r, root.inc)
  62. }
  63. root.inc = 0 // Finished update
  64. if r <= root.mid() {
  65. return root.left.query(l, r)
  66. } else if root.mid()+1 <= l {
  67. return root.right.query(l, r)
  68. } else {
  69. return root.left.query(l, root.mid()) + root.right.query(root.mid()+1, r)
  70. }
  71. }
  72. func main() {
  73. var n int
  74. fmt.Scan(&n)
  75. root := newTree(n)
  76. for i := 1; i <= n; i++ {
  77. root.update(i, i, i)
  78. }
  79. fmt.Println("Sum of 1 ~", n, "is", root.query(1, n))
  80. var l, r, val int
  81. fmt.Print("Update(l, r, val): ")
  82. fmt.Scan(&l, &r, &val)
  83. root.update(l, r, val)
  84. fmt.Print("Query(l, r): ")
  85. fmt.Scan(&l, &r)
  86. fmt.Println(root.query(l, r))
  87. }