- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 52 lines of Go from the credited upstream file 1167F.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 "bufio"5 . "fmt"6 "io"7 "sort"8)9 1011type fenwick67 struct{ t []int }12 13func newFenwickTree67(n int) fenwick67 {14 return fenwick67{make([]int, n+1)}15}16func (f fenwick67) add(i, val int) {17 for ; i < len(f.t); i += i & -i {18 f.t[i] += val19 }20}21func (f fenwick67) sum(i int) (s int) {22 for ; i > 0; i &= i - 1 {23 s += f.t[i]24 }25 return26}27 28func CF1167F(_r io.Reader, out io.Writer) {29 in := bufio.NewReader(_r)30 const mod = 1_000_000_00731 var n int32 Fscan(in, &n)33 a := make([]struct{ v, i int }, n)34 for i := range a {35 Fscan(in, &a[i].v)36 a[i].i = i + 137 }38 sort.Slice(a, func(i, j int) bool { return a[i].v < a[j].v })39 40 ans := 041 f0, f1 := newFenwickTree67(n), newFenwickTree67(n)42 for _, p := range a {43 i := p.i44 ans = (ans + (f0.sum(i-1)*(n+1-i)+(f1.sum(n)-f1.sum(i)+(n+1-i))*i)%mod*p.v) % mod45 f0.add(i, i)46 f1.add(i, n+1-i)47 }48 Fprint(out, ans)49}50 5152