|
| 1 | +#[derive(Clone, PartialEq)] |
| 2 | +enum NodeState { |
| 3 | + UnReached, |
| 4 | + Reached, |
| 5 | + Finished, |
| 6 | +} |
| 7 | + |
| 8 | +fn dikkstra(node_count: usize, graph: &mut Vec<Vec<i32>>) -> Vec<i32> { |
| 9 | + let mut cost_from_start: Vec<i32> = vec![std::i32::MAX; node_count]; |
| 10 | + let mut node_state: Vec<NodeState> = vec![NodeState::UnReached; node_count]; |
| 11 | + // start form 0 |
| 12 | + cost_from_start[0] = 0; |
| 13 | + |
| 14 | + loop { |
| 15 | + let mut is_unfinished_node_fount = false; |
| 16 | + let mut cost_of_this_node = std::i32::MAX; |
| 17 | + let mut cost_calc_finished_node: usize = 0; |
| 18 | + |
| 19 | + for node in 0..node_count { |
| 20 | + if node_state[node] != NodeState::Finished && cost_from_start[node] != std::i32::MAX { |
| 21 | + if cost_from_start[node] < cost_of_this_node{ |
| 22 | + cost_of_this_node = cost_from_start[node]; |
| 23 | + is_unfinished_node_fount = true; |
| 24 | + cost_calc_finished_node = node; |
| 25 | + node_state[node] = NodeState::Reached; |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + if !is_unfinished_node_fount { break; } |
| 31 | + node_state[cost_calc_finished_node] = NodeState::Finished; |
| 32 | + |
| 33 | + for node in 0..node_count { |
| 34 | + if node_state[node] != NodeState::Finished && graph[cost_calc_finished_node][node] != std::i32::MAX { |
| 35 | + if (cost_from_start[cost_calc_finished_node] + graph[cost_calc_finished_node][node]) < cost_from_start[node] { |
| 36 | + cost_from_start[node] = cost_from_start[cost_calc_finished_node] + graph[cost_calc_finished_node][node]; |
| 37 | + node_state[node] = NodeState::Reached; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + cost_from_start |
| 43 | +} |
| 44 | + |
| 45 | +fn main() { |
| 46 | + let node_count: usize = input::read_number(); |
| 47 | + let mut graph: Vec<Vec<i32>> = vec![vec![std::i32::MAX; node_count]; node_count]; |
| 48 | + for _ in 0..node_count { |
| 49 | + let node_info: Vec<usize> = input::read_numline(); |
| 50 | + let node = node_info[0]; |
| 51 | + let node_branch_count = node_info[1]; |
| 52 | + for i in 0..node_branch_count { |
| 53 | + let node_to = node_info[2+i*2]; |
| 54 | + let path_cost = node_info[2+i*2+1] as i32; |
| 55 | + graph[node][node_to] = path_cost; |
| 56 | + } |
| 57 | + } |
| 58 | + let cost_from_start = dikkstra(node_count, &mut graph); |
| 59 | + for (node, cost) in cost_from_start.iter().enumerate() { |
| 60 | + println!("{} {}", node, cost); |
| 61 | + } |
| 62 | +} |
0 commit comments