forked from EndlessCheng/codeforces-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path510C.go
95 lines (87 loc) · 1.6 KB
/
510C.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bufio"
. "fmt"
"io"
)
type graph510C struct {
size int
edges [][]int
inDegree []int
}
func (g *graph510C) add(from, to int) {
g.edges[from] = append(g.edges[from], to)
g.inDegree[to]++
}
func (g *graph510C) topSort() (order []int, acyclic bool) {
queue := []int{}
for i := 0; i < g.size; i++ {
if g.inDegree[i] == 0 {
queue = append(queue, i)
}
}
var v int
for len(queue) > 0 {
v, queue = queue[0], queue[1:]
order = append(order, v)
for _, w := range g.edges[v] {
g.inDegree[w]--
if g.inDegree[w] == 0 {
queue = append(queue, w)
}
}
}
return order, len(order) == g.size
}
// github.com/EndlessCheng/codeforces-go
func Sol510C(reader io.Reader, writer io.Writer) {
in := bufio.NewReader(reader)
out := bufio.NewWriter(writer)
defer out.Flush()
g := &graph510C{
size: 26,
edges: make([][]int, 26),
inDegree: make([]int, 26),
}
var n int
Fscan(in, &n)
var prev, cur string
for ; n > 0; n-- {
Fscan(in, &cur)
minL := len(prev)
if len(cur) < minL {
minL = len(cur)
}
ok := false
for i := 0; i < minL; i++ {
if v, w := prev[i]-'a', cur[i]-'a'; v != w {
g.add(int(v), int(w))
ok = true
break
}
}
if !ok && len(prev) > len(cur) {
Fprint(out, "Impossible")
return
}
prev = cur
}
order, acyclic := g.topSort()
if !acyclic {
Fprint(out, "Impossible")
return
}
done := make([]bool, 26)
for _, c := range order {
Fprintf(out, "%c", 'a'+c)
done[c] = true
}
for i, d := range done {
if !d {
Fprintf(out, "%c", 'a'+i)
}
}
}
//func main() {
// Sol510C(os.Stdin, os.Stdout)
//}