中级农民
- 积分
- 113
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-3-30
- 最后登录
- 1970-1-1
|
搜一下吧,有人贴过答案,比较难理解的是u和v两个数据,意思是一个路径从u走到v,同一个index
比如
u = [2,4]
v = [1,0]
表示2条路径,从2<=>1和4<=>0,注意路径是双向的
- require 'set'
- def find_best_path(n, m, max_t, beauty, u, v, t)
- $max_beauty = 0
- paths = {}
- times = {}
- u.each_with_index do |from, i|
- current = v[i]
- times[i+1] = t[i]
- if paths.key? from
- paths[from] << current
- else
- paths[from] = [current]
- end
- if paths.key? current
- paths[current] << from
- else
- paths[current] = [from]
- end
- end
- dfs(paths, {0 => 1}, [].to_set, 0, beauty[0], max_t, times, beauty)
- $max_beauty
- end
- def dfs(paths, visited_cities, visited_paths, city, current_beauties, time_left, times, beauties)
- if time_left < 0
- return
- end
- if city == 0
- $max_beauty = [$max_beauty, current_beauties].max
- end
- paths[city].each do |next_city|
- path = "#{city}|#{next_city}"
-
- if visited_paths.include?(path)
- next
- else
- visited_paths << path
- end
- city_beauties = current_beauties
- if visited_cities.key?(next_city)
- visited_cities[next_city] += 1
- else
- visited_cities[next_city] = 1
- city_beauties += beauties[next_city]
- end
- spend_time = times[[city, next_city].max]
- dfs(paths, visited_cities, visited_paths, next_city, city_beauties, time_left - spend_time, times, beauties)
- visited_paths.delete(path)
- visited_cities[next_city] -= 1
- if visited_cities[next_city] == 0
- visited_cities.delete(next_city)
- end
- end
- end
- u = [0,1,0]
- v = [1,2,3]
- t = [6,7,10]
- beauty = [5,10,15,20]
- p find_best_path(4, 3, 30, beauty, u, v, t) #30
- u = [0,2,0]
- v = [1,0,3]
- t = [10,13,17]
- beauty = [0,32,10,43]
- p find_best_path(4, 3, 49, beauty, u, v, t) #43
复制代码 |
|