package main import . "fmt" type F struct { s string a, b int64 } type R struct { s string x int64 } func (f *F)Append(e *F) *F{ return &F{ s: f.s + e.s, a: f.a * e.a, b: f.b * e.a + e.b, } } func (f *F) Remove(n *R) (r *R, ok bool) { x := n.x - f.b if x < 1 || x % f.a != 0{ return } x /= f.a ok = x % 2 == 1 || x % 3 == 1 if ok { r = &R{ s:f.s+n.s, x:x, } } return } func (r *R)IsFirst() bool { return r.x==1 } func (f *F)String() string { return Sprintf("%s (%dx+%d)", f.s, f.a, f.b) } func main() { ffs := [][]*F{ []*F{ &F{"A", 2, 1}, &F{"B", 3, 1}, }, } for i := 0; i < 4; i++ { fs := []*F{} for _, x := range ffs[i] { for _, y := range ffs[i] { f := x.Append(y) fs = append(fs, f) } } ffs = append(ffs, fs) } var n R Scan(&n.x) if n.IsFirst() { Println() return } rs:=[]*R{&n} p:=len(ffs)-1 rx:=[]*R{} for { rx=rx[:0] for _,r:=range rs { for _,f:=range ffs[p] { if x,ok:=f.Remove(r);ok { if x.IsFirst() { Println(x.s) return } rx=append(rx,x) } } } if len(rx)==0 { p-- } else { rx,rs=rs,rx } } }