-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathWORDS1.cs
250 lines (202 loc) · 8.75 KB
/
WORDS1.cs
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// https://www.spoj.com/problems/WORDS1/ #euler-path #graph-theory
// Determines if words can be arranged in sequence s.t. end/start letters match.
public static class WORDS1
{
// Tricky part is noticing that instead of words being vertices, words can be edges in
// a graph whose vertices represent letters. Then there's an edge between two vertices
// for each word that starts with the start vertex's letter and ends with the end vertex's
// letter. For example, cat => edge between c and t because if you reach a word ending in c,
// you can ride the edge representing the word cat to any word starting with t, like
// ...c [cat] t... There are fast algorithms for determing Euler path (use all edges once),
// but not for determining Hamiltonian path (uses all vertices once), so this transformation
// really helps. Intuitively I guess the transformation helps so much because it's not the
// words that matter (which words as vertices approach doesn't realize), it's just their
// starting and ending letters (which words as edges approach does realize).
public static bool Solve(string[] words)
{
// For convenience, map the words' starting and ending letters to arbitrary IDs
// between [0, the number of distinct starting and ending letters).
var startAndEndingLetterIDs = words.Select(w => w[0])
.Union(words.Select(w => w[w.Length - 1]))
.Select((l, i) => new { letter = l, ID = i })
.ToDictionary(p => p.letter, p => p.ID);
var directedLetterGraph = new DirectedGraph(startAndEndingLetterIDs.Count);
foreach (string word in words)
{
directedLetterGraph.AddEdge(
startVertexID: startAndEndingLetterIDs[word[0]],
endVertexID: startAndEndingLetterIDs[word[word.Length - 1]]);
}
/* According to Wikipedia: A directed graph has an Eulerian path if and only if at most one
* vertex has (out-degree) − (in-degree) = 1, at most one vertex has (in-degree) − (out-degree) = 1,
* every other vertex has equal in-degree and out-degree, and all of its vertices with nonzero
* degree belong to a single connected component of the underlying undirected graph...
And it's a path, not a cycle that we're looking for--don't need to return to start word. */
if (directedLetterGraph.Vertices.Count(v => v.OutDegree - v.InDegree == 1) > 1
|| directedLetterGraph.Vertices.Count(v => v.InDegree - v.OutDegree == 1) > 1
|| directedLetterGraph.Vertices
.Where(v => v.OutDegree - v.InDegree != 1)
.Where(v => v.InDegree - v.OutDegree != 1)
.Any(v => v.OutDegree != v.InDegree))
return false;
var undirectedLetterGraph = new UndirectedGraph(startAndEndingLetterIDs.Count);
foreach (string word in words)
{
undirectedLetterGraph.AddEdge(
firstVertexID: startAndEndingLetterIDs[word[0]],
secondVertexID: startAndEndingLetterIDs[word[word.Length - 1]]);
}
return undirectedLetterGraph.IsConnected();
}
}
public sealed class DirectedGraph
{
public DirectedGraph(int vertexCount)
{
var vertices = new Vertex[vertexCount];
for (int id = 0; id < vertexCount; ++id)
{
vertices[id] = new Vertex(this, id);
}
Vertices = vertices;
}
public IReadOnlyList<Vertex> Vertices { get; }
public int VertexCount => Vertices.Count;
public void AddEdge(int startVertexID, int endVertexID)
=> AddEdge(Vertices[startVertexID], Vertices[endVertexID]);
public void AddEdge(Vertex startVertex, Vertex endVertex)
=> startVertex.AddNeighbor(endVertex);
public bool HasEdge(int startVertexID, int endVertexID)
=> HasEdge(Vertices[startVertexID], Vertices[endVertexID]);
public bool HasEdge(Vertex startVertex, Vertex endVertex)
=> startVertex.HasNeighbor(endVertex);
public sealed class Vertex : IEquatable<Vertex>
{
private readonly DirectedGraph _graph;
private readonly List<Vertex> _neighbors = new List<Vertex>();
internal Vertex(DirectedGraph graph, int ID)
{
_graph = graph;
this.ID = ID;
}
public int ID { get; }
public IReadOnlyCollection<Vertex> Neighbors => _neighbors;
public int OutDegree => _neighbors.Count;
public int InDegree { get; private set; }
internal void AddNeighbor(int neighborID)
=> _neighbors.Add(_graph.Vertices[neighborID]);
internal void AddNeighbor(Vertex neighbor)
{
_neighbors.Add(neighbor);
++neighbor.InDegree;
}
public bool HasNeighbor(int neighborID)
=> _neighbors.Contains(_graph.Vertices[neighborID]);
public bool HasNeighbor(Vertex neighbor)
=> _neighbors.Contains(neighbor);
public override bool Equals(object obj)
=> (obj as Vertex)?.ID == ID;
public bool Equals(Vertex other)
=> other.ID == ID;
public override int GetHashCode()
=> ID;
}
}
public sealed class UndirectedGraph
{
public UndirectedGraph(int vertexCount)
{
var vertices = new Vertex[vertexCount];
for (int id = 0; id < vertexCount; ++id)
{
vertices[id] = new Vertex(this, id);
}
Vertices = vertices;
}
public IReadOnlyList<Vertex> Vertices { get; }
public int VertexCount => Vertices.Count;
public void AddEdge(int firstVertexID, int secondVertexID)
=> AddEdge(Vertices[firstVertexID], Vertices[secondVertexID]);
public void AddEdge(Vertex firstVertex, Vertex secondVertex)
{
firstVertex.AddNeighbor(secondVertex);
secondVertex.AddNeighbor(firstVertex);
}
public bool HasEdge(int firstVertexID, int secondVertexID)
=> HasEdge(Vertices[firstVertexID], Vertices[secondVertexID]);
public bool HasEdge(Vertex firstVertex, Vertex secondVertex)
=> firstVertex.HasNeighbor(secondVertex);
// DFSes from an arbitrary start vertex, to determine if the whole graph is reachable from it.
public bool IsConnected()
{
var arbitraryStartVertex = Vertices[VertexCount / 2];
var discoveredVertexIDs = new HashSet<int> { arbitraryStartVertex.ID };
var verticesToVisit = new Stack<Vertex>();
verticesToVisit.Push(arbitraryStartVertex);
while (verticesToVisit.Count > 0)
{
var vertex = verticesToVisit.Pop();
foreach (var neighbor in vertex.Neighbors)
{
bool neighborWasDiscoveredForTheFirstTime = discoveredVertexIDs.Add(neighbor.ID);
if (neighborWasDiscoveredForTheFirstTime)
{
verticesToVisit.Push(neighbor);
}
}
}
return discoveredVertexIDs.Count == VertexCount;
}
public sealed class Vertex : IEquatable<Vertex>
{
private readonly UndirectedGraph _graph;
private readonly HashSet<Vertex> _neighbors = new HashSet<Vertex>();
internal Vertex(UndirectedGraph graph, int ID)
{
_graph = graph;
this.ID = ID;
}
public int ID { get; }
public IReadOnlyCollection<Vertex> Neighbors => _neighbors;
public int Degree => _neighbors.Count;
internal void AddNeighbor(int neighborID)
=> _neighbors.Add(_graph.Vertices[neighborID]);
internal void AddNeighbor(Vertex neighbor)
=> _neighbors.Add(neighbor);
public bool HasNeighbor(int neighborID)
=> _neighbors.Contains(_graph.Vertices[neighborID]);
public bool HasNeighbor(Vertex neighbor)
=> _neighbors.Contains(neighbor);
public override bool Equals(object obj)
=> (obj as Vertex)?.ID == ID;
public bool Equals(Vertex other)
=> other.ID == ID;
public override int GetHashCode()
=> ID;
}
}
public static class Program
{
private static void Main()
{
var output = new StringBuilder();
int remainingTestCases = int.Parse(Console.ReadLine());
while (remainingTestCases-- > 0)
{
int wordCount = int.Parse(Console.ReadLine());
string[] words = new string[wordCount];
for (int w = 0; w < wordCount; ++w)
{
words[w] = Console.ReadLine().Trim();
}
output.AppendLine(WORDS1.Solve(words)
? "Ordering is possible."
: "The door cannot be opened.");
}
Console.Write(output);
}
}