blob: 0ddb500b8d054e090870e32e847300352815026c (
plain)
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
|
#!/usr/bin/ruby
#
# See ../README.md
#
#
# Run as: ruby ch-1.rb < input-file
#
ARGF . each_line do
|line|
#
# Read the data; turn the strings into a graph, where the first
# and last character of each string are the nodes, and we have
# a directed edge from the beginning to the end of a string.
#
nodes = {}
graph = {}
line . split . each do
|string|
first = string [0, 1]
last = string [-1, 1]
nodes [first] = 1
nodes [last] = 1
graph [first] ||= {}
graph [last] ||= {}
graph [first] [last] = 1
end
#
# Calculate the transitive closure of the graph using the
# Floyd Warshall algorithm.
#
nodes . each do
|k, _|
nodes . each do
|i, _|
nodes . each do
|j, _|
if graph [i] [k] and graph [k] [j]
then graph [i] [j] = 1
end
end
end
end
#
# We have a loop iff there is node which is reachable from itself.
#
out = 0
nodes . each do
|i, _|
if graph [i] [i]
then out = 1
end
end
puts (out)
end
|