- 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
- 129 lines of Go from the credited upstream file 623A.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 9type graph623A struct {10 size int11 edges [][]bool12 degree []int13 color []int14}15 16func (g *graph623A) add(from, to int) {17 g.edges[from][to] = true18 g.degree[from]++19}20 21func (g *graph623A) addBoth(from, to int) {22 g.add(from, to)23 if from != to {24 g.add(to, from)25 }26}27 28func (g *graph623A) _isBipartite(v int) bool {29 for w, e := range g.edges[v] {30 if e || w == v {31 continue32 }33 if g.color[w] == g.color[v] {34 return false35 }36 if g.color[w] == 0 {37 g.color[w] = 3 - g.color[v]38 if !g._isBipartite(w) {39 return false40 }41 }42 }43 return true44}45 46func (g *graph623A) isBipartite() bool {47 checked := false48 cnt := 049 for i, deg := range g.degree {50 deg = g.size - 1 - deg51 if deg > 0 {52 if checked {53 if g.color[i] == 0 {54 return false55 }56 continue57 }58 g.color[i] = 159 if !g._isBipartite(i) {60 return false61 }62 for w := range g.edges[i] {63 if g.color[w] == 2 {64 cnt++65 }66 }67 checked = true68 }69 }70 if cnt > 0 {71 for v, c := range g.color {72 if c == 1 {73 cntW := 074 for w, e := range g.edges[v] {75 if e || w == v {76 continue77 }78 if g.color[w] == 2 {79 cntW++80 }81 }82 if cntW != cnt {83 return false84 }85 }86 }87 }88 return true89}90 9192func Sol623A(reader io.Reader, writer io.Writer) {93 in := bufio.NewReader(reader)94 out := bufio.NewWriter(writer)95 defer out.Flush()96 97 var n, m int98 Fscan(in, &n, &m)99 g := &graph623A{100 size: n,101 edges: make([][]bool, n),102 degree: make([]int, n),103 color: make([]int, n),104 }105 for i := range g.edges {106 g.edges[i] = make([]bool, n)107 }108 for ; m > 0; m-- {109 var v, w int110 Fscan(in, &v, &w)111 g.addBoth(v-1, w-1)112 }113 114 115 if !g.isBipartite() {116 Fprint(out, "No")117 return118 }119 120 Fprintln(out, "Yes")121 for _, c := range g.color {122 Fprintf(out, "%c", "bac"[c])123 }124}125 126127128129