- 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
- 60 lines of Go from the credited upstream file 1550D.go.
- The implementation keeps its working state in language-native values and containers.
- 1 loop block 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 . "fmt"5 "io"6)7 89func cf1550D(in io.Reader, out io.Writer) {10 const mod = 1_000_000_00711 pow := func(x, n int) int {12 res := 113 for ; n > 0; n /= 2 {14 if n%2 > 0 {15 res = res * x % mod16 }17 x = x * x % mod18 }19 return res20 }21 22 const mx int = 2e523 var F, invF [mx + 1]int24 F[0] = 125 for i := 1; i <= mx; i++ {26 F[i] = F[i-1] * i % mod27 }28 invF[mx] = pow(F[mx], mod-2)29 for i := mx; i > 0; i-- {30 invF[i-1] = invF[i] * i % mod31 }32 C := func(n, k int) int {33 if k < 0 || k > n {34 return 035 }36 return F[n] * invF[k] % mod * invF[n-k] % mod37 }38 39 var T, n, l, r int40 for Fscan(in, &T); T > 0; T-- {41 Fscan(in, &n, &l, &r)42 mn := min(r-n, 1-l)43 ans := C(n, n/2) * mn * (n%2 + 1)44 d, u := 1-mn, n+mn45 for {46 d--47 u++48 m := n - max(l-d, 0) - max(u-r, 0)49 if m < 0 {50 break51 }52 pos := n/2 - max(l-d, 0)53 ans += C(m, pos) + n%2*C(m, pos+1)54 }55 Fprintln(out, ans%mod)56 }57}58 5960