aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnthony Wang2022-03-28 19:00:55 -0500
committerAnthony Wang2022-03-28 19:00:55 -0500
commit252e4ae4ddfb8870aec54ad16424e83d1c7f95d3 (patch)
tree0b3987c0d7fa2af3e3d9bed59f220473052a060e
parent5ec5caa999ea57aaa31019b29d452f32d9122d16 (diff)
Move segment tree to separate file
-rw-r--r--sd.go46
-rw-r--r--segmenttree.go51
2 files changed, 51 insertions, 46 deletions
diff --git a/sd.go b/sd.go
index 0368e70..3cd66b8 100644
--- a/sd.go
+++ b/sd.go
@@ -14,52 +14,6 @@ import (
var verbose = flag.Bool("v", false, "debug output")
var file = flag.String("f", "cards", "cards file")
-type segmentTree struct {
- N int
- seg []int
-}
-
-// Build segment tree
-func (s segmentTree) build(a *sql.Rows, l, r, n int) {
- if l == r {
- a.Next()
- a.Scan(&s.seg[n])
- return
- }
- m := (l + r) >> 1
- s.build(a, l, m, n<<1)
- s.build(a, m+1, r, n<<1|1)
- s.seg[n] = s.seg[n<<1] + s.seg[n<<1|1]
-}
-
-// Update value at index x
-func (s segmentTree) update(x, v, l, r, n int) {
- if l == r {
- s.seg[n] = v
- return
- }
- m := (l + r) >> 1
- if x <= m {
- s.update(x, v, l, m, n<<1)
- } else {
- s.update(x, v, m+1, r, n<<1|1)
- }
- s.seg[n] = s.seg[n<<1] + s.seg[n<<1|1]
-}
-
-// Find element with prefix sum v
-func (s segmentTree) query(v, l, r, n int) (int, int) {
- if l == r {
- return s.seg[n], l
- }
- m := (l + r) >> 1
- if s.seg[n<<1] >= v {
- return s.query(v, l, m, n<<1)
- } else {
- return s.query(v-s.seg[n<<1], m+1, r, n<<1|1)
- }
-}
-
func main() {
flag.Parse()
diff --git a/segmenttree.go b/segmenttree.go
new file mode 100644
index 0000000..e2be46a
--- /dev/null
+++ b/segmenttree.go
@@ -0,0 +1,51 @@
+package main
+
+import (
+ "database/sql"
+)
+
+type segmentTree struct {
+ N int
+ seg []int
+}
+
+// Build segment tree
+func (s segmentTree) build(a *sql.Rows, l, r, n int) {
+ if l == r {
+ a.Next()
+ a.Scan(&s.seg[n])
+ return
+ }
+ m := (l + r) >> 1
+ s.build(a, l, m, n<<1)
+ s.build(a, m+1, r, n<<1|1)
+ s.seg[n] = s.seg[n<<1] + s.seg[n<<1|1]
+}
+
+// Update value at index x
+func (s segmentTree) update(x, v, l, r, n int) {
+ if l == r {
+ s.seg[n] = v
+ return
+ }
+ m := (l + r) >> 1
+ if x <= m {
+ s.update(x, v, l, m, n<<1)
+ } else {
+ s.update(x, v, m+1, r, n<<1|1)
+ }
+ s.seg[n] = s.seg[n<<1] + s.seg[n<<1|1]
+}
+
+// Find element with prefix sum v
+func (s segmentTree) query(v, l, r, n int) (int, int) {
+ if l == r {
+ return s.seg[n], l
+ }
+ m := (l + r) >> 1
+ if s.seg[n<<1] >= v {
+ return s.query(v, l, m, n<<1)
+ } else {
+ return s.query(v-s.seg[n<<1], m+1, r, n<<1|1)
+ }
+}