-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllg-php.php
More file actions
102 lines (78 loc) · 2.05 KB
/
llg-php.php
File metadata and controls
102 lines (78 loc) · 2.05 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
<?php
declare(strict_types=1);
function main()
{
$dic = array_filter(array_map('trim', preg_split('~[\n\r]+~', file_get_contents('php://stdin'))));
$pathFinder = new PathFinder();
$result = $pathFinder->findLongest($dic);
printf('[%s]', implode(' ', $result));
}
main();
class PathFinder
{
/**
* @var []string
*/
private $dic;
/**
* @var []string
*/
private $result = [];
/**
* @var [][]int
*/
private $lookup;
/**
* @var []bool
*/
private $visited = [];
public function findLongest(array $dic): array
{
$this->init($dic);
$this->find(count($dic), []);
return $this->result;
}
private function enter(int $i)
{
$this->visited[$i] = true;
}
private function quit(int $i)
{
$this->visited[$i] = false;
}
private function isVisited(int $i): bool
{
return $this->visited[$i];
}
private function find($currentIndex, array $rest): array
{
foreach ($this->lookup[$currentIndex] as $nextIndex) {
if ($this->isVisited($nextIndex)) {
continue;
}
$this->enter($nextIndex);
$candidate = array_merge($rest, [$this->dic[$nextIndex]]);
$candidate = $this->find($nextIndex, $candidate);
$this->quit($nextIndex);
if (count($candidate) > count($this->result)) {
$this->result = $candidate;
}
}
return $rest;
}
private function init(array $dic)
{
$this->dic = $dic;
foreach($dic as $io => $wo) {
$this->lookup[$io] = [];
foreach($dic as $ii => $wi) {
$lastCharacter = $wo[strlen($wo) - 1];
if ($lastCharacter === $wi[0] && $wo !== $wi) {
$this->lookup[$io][] = $ii;
}
}
}
$this->lookup[count($dic)] = range(0, count($dic) - 1);
$this->visited = array_fill(0, count($dic), false);
}
}