-
Notifications
You must be signed in to change notification settings - Fork 4
/
segtree_test.go
81 lines (75 loc) · 1.36 KB
/
segtree_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package leetcode_test
import (
"fmt"
"math"
"math/rand"
"testing"
"github.com/sebnyberg/leetcode"
"github.com/stretchr/testify/require"
)
func TestSegtreeMin(t *testing.T) {
for i, tc := range []struct {
arr []int
i, j int
want int
}{
{
[]int{7, 1, -10, 13, 2, 61, 4},
0, 6, -10,
},
} {
t.Run(fmt.Sprint(i), func(t *testing.T) {
tree, err := leetcode.NewSegtree(math.MaxInt64, min)
require.NoError(t, err)
tree.Init(tc.arr)
got := tree.QueryRange(tc.i, tc.j)
require.Equal(t, tc.want, got)
})
}
}
func TestSegTreeRand(t *testing.T) {
n := 12938
ub := 921837
lb := -128993
arr := make([]int, n)
for i := range arr {
x := rand.Intn(ub - lb + 1)
arr[i] = x + lb
}
tree, err := leetcode.NewSegtree(math.MaxInt64, min)
require.NoError(t, err)
tree.Init(arr)
for k := 0; k < 4*(n/2); k++ {
lo := rand.Intn(n)
hi := rand.Intn(n)
if lo > hi {
lo, hi = hi, lo
}
want := minRange(arr, lo, hi)
got := tree.QueryRange(lo, hi)
if want != got {
msg := fmt.Sprintf(
"min query for range %v gave the wrong result\n"+
"expected: %v\n"+
"got: %v",
arr[lo:hi+1],
want,
got,
)
t.Fatal(msg)
}
}
}
func minRange(arr []int, i, j int) int {
res := arr[i]
for k := i + 1; k <= j; k++ {
res = min(res, arr[k])
}
return res
}
func min(a, b int) int {
if a < b {
return a
}
return b
}