- 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
- 96 lines of Go from the credited upstream file 510C.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 graph510C struct {10 size int11 edges [][]int12 inDegree []int13}14 15func (g *graph510C) add(from, to int) {16 g.edges[from] = append(g.edges[from], to)17 g.inDegree[to]++18}19 20func (g *graph510C) topSort() (order []int, acyclic bool) {21 queue := []int{}22 for i := 0; i < g.size; i++ {23 if g.inDegree[i] == 0 {24 queue = append(queue, i)25 }26 }27 var v int28 for len(queue) > 0 {29 v, queue = queue[0], queue[1:]30 order = append(order, v)31 for _, w := range g.edges[v] {32 g.inDegree[w]--33 if g.inDegree[w] == 0 {34 queue = append(queue, w)35 }36 }37 }38 return order, len(order) == g.size39}40 4142func Sol510C(reader io.Reader, writer io.Writer) {43 in := bufio.NewReader(reader)44 out := bufio.NewWriter(writer)45 defer out.Flush()46 47 g := &graph510C{48 size: 26,49 edges: make([][]int, 26),50 inDegree: make([]int, 26),51 }52 var n int53 Fscan(in, &n)54 var prev, cur string55 for ; n > 0; n-- {56 Fscan(in, &cur)57 minL := len(prev)58 if len(cur) < minL {59 minL = len(cur)60 }61 ok := false62 for i := 0; i < minL; i++ {63 if v, w := prev[i]-'a', cur[i]-'a'; v != w {64 g.add(int(v), int(w))65 ok = true66 break67 }68 }69 if !ok && len(prev) > len(cur) {70 Fprint(out, "Impossible")71 return72 }73 prev = cur74 }75 76 order, acyclic := g.topSort()77 if !acyclic {78 Fprint(out, "Impossible")79 return80 }81 done := make([]bool, 26)82 for _, c := range order {83 Fprintf(out, "%c", 'a'+c)84 done[c] = true85 }86 for i, d := range done {87 if !d {88 Fprintf(out, "%c", 'a'+i)89 }90 }91}92 93949596