- 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
- 70 lines of Go from the credited upstream file 190C.go.
- The implementation keeps its working state in language-native values and containers.
- 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 pair190C struct {10 isInt bool11 a, b *pair190C12}13 14func (p *pair190C) read(in *bufio.Reader) bool {15 var s string16 if n, _ := Fscan(in, &s); n == 0 {17 return false18 }19 if s == "int" {20 p.isInt = true21 return true22 }23 p.a = &pair190C{}24 if !p.a.read(in) {25 return false26 }27 p.b = &pair190C{}28 if !p.b.read(in) {29 return false30 }31 return true32}33 34func (p *pair190C) print(out *bufio.Writer) {35 if p.isInt {36 Fprint(out, "int")37 return38 }39 Fprint(out, "pair<")40 p.a.print(out)41 Fprint(out, ",")42 p.b.print(out)43 Fprint(out, ">")44}45 46func Sol190C(reader io.Reader, writer io.Writer) {47 in := bufio.NewReader(reader)48 out := bufio.NewWriter(writer)49 defer out.Flush()50 51 const e = "Error occurred"52 var n int53 Fscan(in, &n)54 p := &pair190C{}55 if !p.read(in) {56 Fprint(out, e)57 return58 }59 var s string60 if n, _ := Fscan(in, &s); n > 0 {61 Fprint(out, e)62 return63 }64 p.print(out)65}66 67686970