#!/usr/bin/ruby # Finding Sophie. # Jan. 2010 # tom.luo@mgail.com MAX = 1000000 # MAX = 1073741823 locations = [] $min_time = MAX $probabilities =[] $connHash = {} $searched = [] file_name=ARGV[0] file=File.open(file_name,"r") $n_locations= file.readline.to_i $n_locations.times do |i| location_probability = file.readline.split(" ") locations << location_probability[0] # locations.uniq! "there will be no duplicate names" in the problem statement $probabilities << location_probability[1].to_f end $n_locations.times do |i| $n_locations.times do |j| $connHash[i] ||= {} $connHash[j] ||= {} $connHash[i][j] = MAX end end $n_conn = file.readline.to_i $n_conn.times do |i| connection = file.readline.split(" ") from = locations.index(connection[0]) to = locations.index(connection[1]) time = connection[2].to_i $connHash[from] ||= {} $connHash[to] ||= {} $connHash[from][to] = $connHash[to][from] = time end $n_locations.times do |k| $n_locations.times do |i| $n_locations.times do |j| $connHash[i][j] = [$connHash[i][j], $connHash[i][k] + $connHash[k][j]].min if i != j end end end $n_locations.times do |i| for j in i..($n_locations-1) do if i != j and $connHash[i][j] == MAX then puts "-1.00\n" Process.exit end end end $n_locations.times do |i| $searched[i]=false end def search(node, increment, probability) $searched[node] = true probability -= $probabilities[node] finished = true $n_locations.times do |i| if not $searched[i] then finished = false if ((increment + (probability * $connHash[node][i])) < $min_time) then search(i, increment + probability*$connHash[node][i], probability) end end end $searched[node]=false if finished then if ((increment < $min_time) and ($min_time != -1)) || ($min_time < 0) then $min_time = increment end end end search(0,0,1) printf("%.2f\n",$min_time)