So the code is to calculate the cost of each colony, where the earth is the top one, like a tree,and the rules are the cost for the leafs is the cost they need to take to reach earth, and for the middle nods it depends they can go to the earth or to other leaf that needs to pass by them to reach the earth, the input is somelike like this [(1,2,5);(2,3,15)....], the 'a' is the first planet, the 'b' is the destination planet and 'c' is the cost that takes to make the travel between those two then with more inputs it creates a tree.
let p = read_int() (*Input com o numero de planetas*)
(*let () = if p < 0 then failwith "Valor Incorreto" Verifica se o numero de planetas é pelo menos positivo*)
let m = read_int() (*Input com o numero de wormholes*)
let () = if m < p-1 || m > p || m = p then failwith "Valor Incorreto" (*Verifica se o numero de wormholes e -1 c*)
let buracos = Array.make m (0, 0, 0) (*Cria o tuplo com os inputs*)
let conexoes m buracos = (*Le os inputs e coloca em tuplos*)
for i = 0 to m - 1 do
buracos.(i) <- Scanf.scanf " %d %d %d" (fun a b c -> a, b, c)
done
let colonias lburacos p =
let x = List.filter (fun (a, _, _) -> a = p) lburacos
in List.map (fun (_, b, c) -> (b, c)) x
let () = conexoes m buracos
let lburacos = Array.to_list buracos
let resultados = Array.make p 0
let pais buracos p =
let x = List.filter (fun (_, b, _) -> b = p) buracos
in List.map (fun (a, _, c) -> (a, c)) x
let rec calc_raizes buracos p custo =
let anteriores = pais buracos p in
List.iter (fun (a, c) -> resultados.(a - 1) <- max resultados.(a - 1) (custo + c); calc_raizes buracos a (custo + c)) anteriores
let rec calc_folhas buracos p custo =
let proximos = colonias buracos p in
if proximos = [] then calc_raizes buracos p 0
else List.iter (fun (a, b) -> resultados.(a - 1) <- custo + b; calc_folhas buracos a (custo + b)) proximos
let () = calc_folhas lburacos 1 0
let () = resultados.(0) <- Array.fold_left max 0 resultados
let () = Array.iter (Printf.printf "%d\n") resultados