-
Notifications
You must be signed in to change notification settings - Fork 46
/
ml.ml
60 lines (56 loc) · 1.64 KB
/
ml.ml
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
type route = {
dest: int;
cost: int;
}
let build_array node =
let a = Array.make (2 * (List.length node)) 0 in
let rec fill i = function
| [] -> a
| hd::tl ->
Array.set a i hd.dest;
Array.set a (i+1) hd.cost;
fill (i+2) tl
in
fill 0 node
let readPlaces () =
let f = open_in "agraph" in
let next_int () = Scanf.fscanf f " %d" (fun n -> n) in
let n = next_int () in
let nodes = Array.make n [] in
begin
try while true do
let node = next_int () in
let dest = next_int () in
let cost = next_int () in
nodes.(node) <- ({dest; cost} :: nodes.(node));
done with _ -> close_in f
end;
let nodes = Array.map build_array nodes in
(nodes, n)
let rec getLongestPath nodes nodeID visited =
visited.(nodeID) <- true;
let rec loop nodes nodeID visited i maxDist =
if i < 0 then maxDist
else
let neighbour = nodes.(nodeID) in
let dest = neighbour.(i) in
let cost = neighbour.(i+1) in
if visited.(dest)
then loop nodes nodeID visited (i-2) maxDist
else
let dist = cost + getLongestPath nodes dest visited in
let newMax = if dist > maxDist then dist else maxDist in
loop nodes nodeID visited (i-2) newMax
in
let (max: int) =
loop nodes nodeID visited (Array.length nodes.(nodeID) - 2) 0
in
visited.(nodeID) <- false;
max;;
let () =
let (nodes, numNodes) = readPlaces() in
let visited = Array.init numNodes (fun x -> false) in
let start = Unix.gettimeofday() in
let len = getLongestPath nodes 0 visited in
Printf.printf "%d LANGUAGE Ocaml %d\n"
len (int_of_float @@ 1000. *. (Unix.gettimeofday() -. start))