- 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
- 94 lines of Go from the credited upstream file 1794D.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)8 910const mod94 = 99824435311 12func pow94(x int64, n int) (res int64) {13 x %= mod9414 res = 115 for ; n > 0; n >>= 1 {16 if n&1 > 0 {17 res = res * x % mod9418 }19 x = x * x % mod9420 }21 return22}23 24type comb94 struct{ f, invF []int64 }25 26func newComb94(mx int) *comb94 {27 c := &comb94{[]int64{1}, []int64{1}}28 c.init(mx)29 return c30}31 32func (c *comb94) init(mx int) {33 n := len(c.f)34 c.f = append(make([]int64, 0, mx+1), c.f...)[:mx+1]35 for i := n; i <= mx; i++ {36 c.f[i] = c.f[i-1] * int64(i) % mod9437 }38 c.invF = append(make([]int64, 0, mx+1), c.invF...)[:mx+1]39 c.invF[mx] = pow94(c.f[mx], mod94-2)40 for i := mx; i > n; i-- {41 c.invF[i-1] = c.invF[i] * int64(i) % mod9442 }43}44 45func (c *comb94) factorial(n int) int64 {46 if n >= len(c.f) {47 c.init(n * 2)48 }49 return c.f[n]50}51 52func (c *comb94) invFactorial(n int) int64 {53 if n >= len(c.f) {54 c.init(n * 2)55 }56 return c.invF[n]57}58 59func CF1794D(_r io.Reader, out io.Writer) {60 in := bufio.NewReader(_r)61 const mx int = 1e662 np := [mx + 1]bool{true, true}63 for i := 2; i <= mx; i++ {64 if !np[i] {65 for j := i * i; j <= mx; j += i {66 np[j] = true67 }68 }69 }70 71 var n, v int72 Fscan(in, &n)73 cnt := map[int]int{}74 for i := 0; i < n*2; i++ {75 Fscan(in, &v)76 cnt[v]++77 }78 79 cm := newComb94(n)80 f := make([]int64, n+1)81 f[0] = cm.factorial(n)82 for v, c := range cnt {83 for j := n; j >= 0; j-- {84 f[j] = f[j] * cm.invFactorial(c) % mod9485 if j > 0 && !np[v] {86 f[j] = (f[j] + f[j-1]*cm.invFactorial(c-1)) % mod9487 }88 }89 }90 Fprint(out, f[n])91}92 9394