Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. use std::io::{BufferedReader, File};
  2.  
  3. struct Route {
  4. dest: i32,
  5. cost: i32,
  6. }
  7.  
  8. struct Node {
  9. neighbours: Vec<Route>,
  10. }
  11.  
  12. fn read_places() -> Vec<Node> {
  13. let path = Path::new("agraph");
  14. let mut file = BufferedReader::new(File::open(&path));
  15. let mut lines = file.lines().map(|x| x.unwrap());
  16.  
  17. let numnodes: uint = match lines.next() {
  18. Some(num) => from_str(num.as_slice().trim()).unwrap(),
  19. _ => panic!("Error, first line of file should describe the amount of nodes")
  20. };
  21.  
  22. let mut nodes = Vec::from_fn(numnodes, |_| Node { neighbours: vec![] });
  23.  
  24. for line in lines {
  25. let nums: Vec<&str> = line.split(' ').collect();
  26.  
  27. let node : uint = from_str(nums[0] ).expect("Error: node id was not a uint");
  28. let neighbour: i32 = from_str(nums[1] ).expect("Error: neighbour id was not an int");
  29. let cost : i32 = from_str(nums[2].trim()).expect("Error: route cost was not an int");
  30.  
  31. nodes[node].neighbours.push(Route {dest: neighbour, cost: cost});
  32. }
  33.  
  34. return nodes;
  35. }
  36.  
  37. fn get_longest_path(nodes: &Vec<Node>, node_id: i32, visited: &mut Vec<bool>) -> i32 {
  38. visited[node_id as uint] = true;
  39. let mut max = 0i32;
  40.  
  41. for neighbour in nodes[node_id as uint].neighbours.iter() {
  42. if !visited[neighbour.dest as uint] {
  43. let dist = neighbour.cost + get_longest_path(nodes, neighbour.dest, visited);
  44.  
  45. if dist > max {
  46. max = dist;
  47. }
  48. }
  49. }
  50.  
  51. visited[node_id as uint] = false;
  52. return max;
  53. }
  54.  
  55. fn main() {
  56. let nodes = read_places();
  57. let mut visited = Vec::from_elem(nodes.len(), false);
  58. let path = get_longest_path(&nodes, 0, &mut visited);
  59. println!("{}", path);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement