- 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
- 73 lines of Go from the credited upstream file 663A.go.
- The implementation visibly relies on sequence storage.
- 1 loop block 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 . "fmt"5 "io"6)7 89func CF663A(in io.Reader, out io.Writer) {10 var s string11 var x, y, n int12 a := []string{}13 for {14 Fscan(in, &s, &s)15 if s == "-" {16 y++17 } else {18 x++19 }20 if s == "=" {21 break22 }23 a = append(a, s)24 }25 Fscan(in, &n)26 if n+y > n*x || x > n+n*y {27 Fprint(out, "Impossible")28 return29 }30 Fprintln(out, "Possible")31 if n+y >= x {32 q := (n + y) / x33 c := (n + y) % x34 if c > 0 {35 Fprint(out, q+1)36 c--37 } else {38 Fprint(out, q)39 }40 for _, s := range a {41 if s == "+" {42 if c > 0 {43 Fprint(out, " + ", q+1)44 c--45 } else {46 Fprint(out, " + ", q)47 }48 } else {49 Fprint(out, " - 1")50 }51 }52 } else {53 q := (x - n) / y54 c := (x - n) % y55 Fprint(out, 1)56 for _, s := range a {57 if s == "-" {58 if c > 0 {59 Fprint(out, " - ", q+1)60 c--61 } else {62 Fprint(out, " - ", q)63 }64 } else {65 Fprint(out, " + 1")66 }67 }68 }69 Fprint(out, " = ", n)70}71 7273