- 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
- 89 lines of Go from the credited upstream file 1819D.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 910func cf1819D(in io.Reader, _w io.Writer) {11 out := bufio.NewWriter(_w)12 defer out.Flush()13 var T, n, m, k int14 vis := [2e5 + 1]int{}15 for Fscan(in, &T); T > 0; T-- {16 Fscan(in, &n, &m)17 a := make([][]int, n+1)18 used := []int{}19 for i := 1; i <= n; i++ {20 Fscan(in, &k)21 a[i] = make([]int, k)22 for j := range a[i] {23 Fscan(in, &a[i][j])24 used = append(used, a[i][j])25 }26 }27 28 rem := make([]int, n+2)29 zero := make([]int, n+2)30 31 ok := false32 cur := 033 for i := n; i > 0; i-- {34 for _, x := range a[i] {35 cur = min(cur+1, m)36 if vis[x] != 0 {37 ok = true38 }39 vis[x] = i40 }41 if len(a[i]) == 0 {42 cur = m43 }44 if ok {45 rem[i] = 046 } else {47 rem[i] = cur48 }49 }50 51 for _, x := range used {52 vis[x] = 053 }54 55 empty := 056 ans := rem[1]57 limit := 058 59 for i := 1; i <= n; i++ {60 zero[i+1] = zero[i]61 if len(a[i]) == 0 {62 ans = max(ans, rem[i+1])63 empty = i64 zero[i+1] = i65 continue66 }67 68 mx := empty69 for _, x := range a[i] {70 mx = max(mx, vis[x])71 }72 if mx > 0 && limit <= zero[mx] {73 zero[i+1] = i74 ans = max(ans, rem[i+1])75 }76 for _, x := range a[i] {77 limit = max(limit, vis[x])78 vis[x] = i79 }80 }81 Fprintln(out, ans)82 for _, x := range used {83 vis[x] = 084 }85 }86}87 8889