- 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
- 53 lines of Go from the credited upstream file 708B.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 . "fmt"5 "io"6 "math"7 "strings"8)9 1011func CF708B(in io.Reader, out io.Writer) {12 var c00, c01, c10, c11 int13 Fscan(in, &c00, &c01, &c10, &c11)14 f := func(c int) int {15 x := (1 + int(math.Sqrt(float64(1+8*int64(c))))) / 216 if x*(x-1)/2 == c {17 return x18 }19 return -120 }21 c0, c1 := f(c00), f(c11)22 if c0 < 0 || c1 < 0 {23 Fprint(out, "Impossible")24 return25 }26 27 if c01 == 0 && c10 == 0 {28 if c00 > 0 && c11 > 0 {29 Fprint(out, "Impossible")30 } else if c11 == 0 {31 Fprint(out, strings.Repeat("0", c0))32 } else {33 Fprint(out, strings.Repeat("1", c1))34 }35 return36 }37 38 if c01+c10 != c0*c1 {39 Fprint(out, "Impossible")40 return41 }42 left1, right0 := c10/c0, c10%c043 ans := strings.Repeat("1", left1) + strings.Repeat("0", c0-right0)44 if right0 > 0 {45 ans += "1" + strings.Repeat("0", right0)46 c1--47 }48 ans += strings.Repeat("1", c1-left1)49 Fprint(out, ans)50}51 5253