Advertisement
troydota

Untitled

May 21st, 2021
1,273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.77 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type BitTree []int
  6.  
  7. func main() { // O(nlogn)
  8.     input := []int{-1, 3, -4, 5, 1, -6, 2, 1}
  9.     tr := ConstructorBIT(input) // O(nlogn)
  10.     total := tr.Sum(len(input) - 1)
  11.     for i := 1; i < len(input); i++ {
  12.         n := tr.Sum(i - 1) // O(nlogn)
  13.         if total-n-input[i] == n {
  14.             fmt.Println(i)
  15.             return
  16.         }
  17.     }
  18.     fmt.Println(-1)
  19. }
  20.  
  21. func ConstructorBIT(input []int) BitTree {
  22.     t := make(BitTree, len(input)+1)
  23.     for i, v := range input {
  24.         t.Update(i, v)
  25.     }
  26.     return t
  27. }
  28.  
  29. func (t BitTree) Sum(index int) int {
  30.     s := 0
  31.     index++
  32.     for index > 0 {
  33.         s += t[index]
  34.         index -= index & (-index)
  35.     }
  36.     return s
  37. }
  38.  
  39. func (t BitTree) Update(index, value int) {
  40.     index++
  41.     for index < len(t) {
  42.         t[index] += value
  43.         index += index & (-index)
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement