- 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
- 105 lines of Go from the credited upstream file 653E.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 cf653E(_r io.Reader, out io.Writer) {11 in := bufio.NewReader(_r)12 var n, m, k, ts int13 Fscan(in, &n, &m, &k)14 ban := make([][]int, n)15 for ; m > 0; m-- {16 var v, w int17 Fscan(in, &v, &w)18 v--19 w--20 ban[v] = append(ban[v], w)21 ban[w] = append(ban[w], v)22 }23 24 if len(ban[0])+k >= n {25 Fprint(out, "impossible")26 return27 }28 29 30 maxV := 131 for v := 1; v < n; v++ {32 if len(ban[v]) < len(ban[maxV]) {33 maxV = v34 }35 }36 37 ccNum := n - 138 fa := make([]int, n)39 for i := range fa {40 fa[i] = i41 }42 var find func(int) int43 find = func(x int) int {44 if fa[x] != x {45 fa[x] = find(fa[x])46 }47 return fa[x]48 }49 merge := func(from, to int) {50 f, t := find(from), find(to)51 if f == t {52 return53 }54 ccNum--55 fa[f] = t56 }57 same := func(x, y int) bool { return find(x) == find(y) }58 59 has := make([]int, n)60 mergeInv := func(v int) {61 ts++62 has[v] = ts63 for _, w := range ban[v] {64 has[w] = ts65 }66 for i := 1; i < n; i++ {67 if has[i] != ts {68 merge(i, v)69 }70 }71 }72 mergeInv(maxV)73 for v := 1; v < n; v++ {74 if !same(v, maxV) {75 mergeInv(v)76 }77 }78 79 if ccNum > k {80 Fprint(out, "impossible")81 return82 }83 84 ts++85 for _, w := range ban[0] {86 has[w] = ts87 }88 vis := make([]bool, n)89 for i := 1; i < n; i++ {90 if has[i] != ts && !vis[find(i)] {91 vis[find(i)] = true92 }93 }94 for i := 1; i < n; i++ {95 if !vis[find(i)] {96 97 Fprint(out, "impossible")98 return99 }100 }101 Fprint(out, "possible")102}103 104105