結果
問題 |
No.1 道のショートカット
|
ユーザー |
![]() |
提出日時 | 2025-09-05 21:00:11 |
言語 | OCaml (5.2.1) |
結果 |
AC
|
実行時間 | 5 ms / 5,000 ms |
コード長 | 2,693 bytes |
コンパイル時間 | 2,150 ms |
コンパイル使用メモリ | 22,768 KB |
実行使用メモリ | 7,716 KB |
最終ジャッジ日時 | 2025-09-05 21:00:15 |
合計ジャッジ時間 | 3,233 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 40 |
ソースコード
let () = (* Read number of nodes, budget, and number of edges *) let num_nodes, budget, num_edges = Scanf.scanf "%d %d %d " (fun a b c -> (a, b, c)) in (* Arrays to store edge information *) let source_nodes = Array.make num_edges 0 in let target_nodes = Array.make num_edges 0 in let edge_costs = Array.make num_edges 0 in let edge_times = Array.make num_edges 0 in (* Read source nodes (convert to 0-based indexing) *) for i = 0 to num_edges - 1 do source_nodes.(i) <- (Scanf.scanf "%d " (fun x -> x)) - 1 done; (* Read target nodes (convert to 0-based indexing) *) for i = 0 to num_edges - 1 do target_nodes.(i) <- (Scanf.scanf "%d " (fun x -> x)) - 1 done; (* Read edge costs *) for i = 0 to num_edges - 1 do edge_costs.(i) <- Scanf.scanf "%d " (fun x -> x) done; (* Read edge times *) for i = 0 to num_edges - 1 do edge_times.(i) <- Scanf.scanf "%d " (fun x -> x) done; (* Create adjacency list for the graph *) let graph = Array.make num_nodes [] in for i = 0 to num_edges - 1 do let source = source_nodes.(i) in let target = target_nodes.(i) in let cost = edge_costs.(i) in let time = edge_times.(i) in graph.(source) <- (target, cost, time) :: graph.(source) done; (* Initialize DP table *) let infinity = 1000000000 in let dp = Array.make_matrix num_nodes (budget + 1) infinity in (* Start at node 0 with full budget, time = 0 *) dp.(0).(budget) <- 0; (* Dynamic programming: for each node, process all possible budget states *) for current_node = 0 to num_nodes - 1 do for remaining_budget = budget downto 0 do (* Skip if this state is unreachable *) if dp.(current_node).(remaining_budget) <> infinity then (* Process all outgoing edges from current node *) List.iter (fun (target, cost, time) -> (* Check if we have enough budget to take this edge *) if remaining_budget >= cost then let new_budget = remaining_budget - cost in let new_time = dp.(current_node).(remaining_budget) + time in (* Update if we found a better path *) if new_time < dp.(target).(new_budget) then dp.(target).(new_budget) <- new_time ) graph.(current_node) done done; (* Find the minimum time to reach the last node (node n-1) *) let min_time = ref infinity in for remaining_budget = 0 to budget do if dp.(num_nodes - 1).(remaining_budget) < !min_time then min_time := dp.(num_nodes - 1).(remaining_budget) done; (* Output result *) if !min_time = infinity then print_endline "-1" else Printf.printf "%d\n" !min_time