-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest_path.fold
49 lines (34 loc) · 1.05 KB
/
Longest_path.fold
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
load strutils
load sequtils
load times
type Route =
{ dest :: int
cost :: int }
type Node =
{ neighbours :: Seq[Route] }
let lines = split (file "agraph")
let numNodes = lines[0].parseInt
var nodes = newSeqWith(numNodes, Node(neighbours: newSeq[Route]()))
var visited = newSeq[bool](numNodes)
map lines : l ->
nums =
for i in 1..lines.high:
let nums = lines[i].split(' ')
if nums.len < 3:
break
let node = nums[0].parseInt
let neighbour = nums[1].parseInt
let cost = nums[2].parseInt
nodes[node].neighbours.add(Route(dest: neighbour, cost: cost))
proc getLongestPath(nodeId: int): int =
visited[nodeId] = true
for neighbour in nodes[nodeId].neighbours:
if not visited[neighbour.dest]:
let dist = neighbour.cost + getLongestPath(neighbour.dest)
if dist > result:
result = dist
visited[nodeId] = false
let start = cpuTime()
let result = getLongestPath(0)
let duration = cpuTime() - start
echo result, " LANGUAGE Nim ", int(duration * 1000)