- 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
- 63 lines of Go from the credited upstream file 689E.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 1011func CF689E(_r io.Reader, out io.Writer) {12 in := bufio.NewReader(_r)13 const mod int64 = 1e9 + 714 pow := func(x, n int64) (res int64) {15 res = 116 for ; n > 0; n >>= 1 {17 if n&1 > 0 {18 res = res * x % mod19 }20 x = x * x % mod21 }22 return res23 }24 25 var n, k, l, r, s int26 Fscan(in, &n, &k)27 mx := int64(n)28 F := make([]int64, mx+1)29 F[0] = 130 for i := int64(1); i <= mx; i++ {31 F[i] = F[i-1] * i % mod32 }33 invF := make([]int64, mx+1)34 invF[mx] = pow(F[mx], mod-2)35 for i := mx; i > 0; i-- {36 invF[i-1] = invF[i] * i % mod37 }38 C := func(n, k int) int64 { return F[n] * invF[k] % mod * invF[n-k] % mod }39 40 d := map[int]int{}41 for ; n > 0; n-- {42 Fscan(in, &l, &r)43 d[l]++44 d[r+1]--45 }46 type pair struct{ p, d int }47 pd := make([]pair, 0, len(d))48 for p, d := range d {49 pd = append(pd, pair{p, d})50 }51 sort.Slice(pd, func(i, j int) bool { return pd[i].p < pd[j].p })52 ans := int64(0)53 for i, p := range pd {54 if s >= k {55 ans = (ans + C(s, k)*int64(p.p-pd[i-1].p)) % mod56 }57 s += p.d58 }59 Fprint(out, ans)60}61 6263