/
main.go
68 lines (61 loc) · 1.18 KB
/
main.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
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func lowBit(index int) int {
return index & -index
}
func add(index, num int, tree []int) {
l := len(tree)
for index < l {
tree[index] += num
index += lowBit(index)
}
}
func sum(index int, tree []int) (ans int) {
for index >= 1 {
ans += tree[index]
index &= index - 1
}
return ans
}
func Init(array []int) []int {
l := len(array)
ans := make([]int, l+1)
for i := 0; i < l; i++ {
index := i + 1
ans[index] += array[i]
fatherIndex := index + lowBit(index)
if fatherIndex <= l {
ans[fatherIndex] += ans[index]
}
}
return ans
}
func main() {
p130(os.Stdin, os.Stdout)
}
func p130(_r io.Reader, _w io.Writer) {
input, output := bufio.NewReader(_r), bufio.NewWriter(_w)
var n, q int
fmt.Fscan(input, &n, &q)
array := make([]int, n)
for i := 0; i < n; i++ {
fmt.Fscan(input, &array[i])
}
tree := Init(array)
for i := 0; i < q; i++ {
operate := [3]int{}
fmt.Fscan(input, &operate[0], &operate[1], &operate[2])
if operate[0] == 1 {
add(operate[1], operate[2], tree)
} else if operate[0] == 2 {
ans := sum(operate[2], tree) - sum(operate[1]-1, tree)
fmt.Fprintln(output, ans)
}
}
output.Flush()
}