-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
executable file
·120 lines (92 loc) · 2.88 KB
/
Program.cs
File metadata and controls
executable file
·120 lines (92 loc) · 2.88 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace llg_csharp
{
class Program
{
static void Main(string[] args)
{
var dic = new List<string>();
string s;
while ((s = Console.ReadLine()) != null)
{
dic.Add(s);
}
var pathFinder = new PathFinder();
var result = pathFinder.FindLongest(dic);
Console.WriteLine(String.Join(" ", result));
}
}
class PathFinder
{
private List<string> Dic;
private byte[][] Lookup;
private bool[] Visited;
private List<byte> Result;
public List<string> FindLongest(List<string> dic)
{
Init(dic);
Find(dic.Count, new byte[dic.Count], 0);
var result = Result.Select(i => dic[i]).ToList();
return result;
}
private bool IsVisited(int index)
{
return Visited[index];
}
private void Visit(int index)
{
Visited[index] = true;
}
private void Exit(int index)
{
Visited[index] = false;
}
private byte[] Find(int currentIndex, byte[] rest, int depth)
{
var list = Lookup[currentIndex];
for (var i = 0; i < list.Length; ++i)
{
var nextIndex = list[i];
if (IsVisited(nextIndex))
{
continue;
}
Visit(nextIndex);
rest[depth] = nextIndex;
var candidate = Find(nextIndex, rest, depth + 1);
Exit(nextIndex);
if (depth + 1 > Result.Count)
{
Result = candidate.Take(depth + 1).ToList();
}
}
return rest;
}
private void Init(List<string> dic)
{
Dic = dic;
Lookup = new byte[dic.Count + 1][];
for (var io = 0; io < dic.Count; ++io)
{
var wo = dic[io];
var lastCharacter = wo[wo.Length - 1];
var entries = new List<byte>(dic.Count);
for (var ii = 0; ii < dic.Count; ++ii)
{
var wi = dic[ii];
if (lastCharacter == wi[0] && wo != wi)
{
entries.Add((byte)ii);
}
}
Lookup[io] = entries.ToArray();
}
Lookup[dic.Count] = Enumerable.Range(0, dic.Count - 1).Select(v => (byte)v).ToArray();
Visited = new bool[dic.Count];
Result = new List<byte>();
}
}
}