Algorithm 参观博物馆的最低费用
我最近参加了一次招聘挑战,看到了这个问题: 给定的Algorithm 参观博物馆的最低费用,algorithm,data-structures,graph,Algorithm,Data Structures,Graph,我最近参加了一次招聘挑战,看到了这个问题: 给定的N博物馆地图,具有给定的入场费和连接博物馆的M加权双向道路。从每个博物馆开始,我们需要找到参观至少一个博物馆的最低成本费用将是旅行道路重量和参观博物馆入场费的总和。 输入格式: Number of museums N and number of roads M Entry fees of each museum Next M lines will have x, y, z where museum x and museum y are conne
N
博物馆地图,具有给定的入场费和连接博物馆的M
加权双向道路。从每个博物馆开始,我们需要找到参观至少一个博物馆的最低成本费用将是旅行道路重量和参观博物馆入场费的总和。
输入格式:
Number of museums N and number of roads M
Entry fees of each museum
Next M lines will have x, y, z where museum x and museum y are connected by road with weight z
输出格式:
N integers where ith integer denotes minimum cost to reach and enter any museum starting from ith museum.
输入:
5 4
1 2 3 1 5
1 2 1
2 3 1
3 4 1
4 5 1
输出:
1 2 2 1 2
在这里,从1号博物馆开始,我们可以直接参观1号博物馆,入场费为1美元。
从3号博物馆开始,我们可以花2美元参观4号博物馆
我需要一种比从图的每个节点应用dijsktra更有效的优化方法。约束很高,足以避免floyd-warshall算法
提前感谢。您的图形以“博物馆外X”节点和它们之间的道路边缘开始 您需要一个如下所示的条目优先级队列:
{
cost: xxx,
outside_museum: xxx
}
{
cost: entry_fee_for_museum_x,
outside_museum: x
}
while queue not empty:
get lowest cost item from queue
if it's museum is not in cost_to_museum:
cost_to_museum[item.outside_museum] = item.cost
for each road connecting to museum:
add to queue an entry for traveling to here from there
(That is, location is the other museum, cost is road + current cost)
您可以使用如下所示的条目对其进行初始化:
{
cost: xxx,
outside_museum: xxx
}
{
cost: entry_fee_for_museum_x,
outside_museum: x
}
while queue not empty:
get lowest cost item from queue
if it's museum is not in cost_to_museum:
cost_to_museum[item.outside_museum] = item.cost
for each road connecting to museum:
add to queue an entry for traveling to here from there
(That is, location is the other museum, cost is road + current cost)
保留一本字典,将博物馆映射到最低成本,如cost\u to\u museum
现在,您的循环如下所示:
{
cost: xxx,
outside_museum: xxx
}
{
cost: entry_fee_for_museum_x,
outside_museum: x
}
while queue not empty:
get lowest cost item from queue
if it's museum is not in cost_to_museum:
cost_to_museum[item.outside_museum] = item.cost
for each road connecting to museum:
add to queue an entry for traveling to here from there
(That is, location is the other museum, cost is road + current cost)
这应该及时执行
O((n+m)log(n+m))
其中n
是博物馆的数量,m
是道路的数量。。。。那么,你试过什么了吗?:)我试着在指定的时间从每个节点应用dijsktra,但是,当然,它超出了执行时间限制?大多数时候,你可以早点停下来。假设您有一个成本为c
(您已经找到的博物馆)的当前解决方案,当前节点的道路重量为r
,您尚未访问的博物馆最低费用为m
。如果r+m>=c
,您就可以停止,因为您无法找到更好的解决方案。让博物馆保持树状结构,在那里你可以动态地添加和删除项目,并以最快的速度获得最小的速度(类似于图像处理中的最小过滤器)。我认为在这个问题上,我们不能过早地停止dijsktra。我在寻找从一个节点到另一个节点的最短距离d[I],并考虑进入该博物馆的成本为d[I]+e[I],我在寻找这个数量的最小值。你为什么认为我展示的策略不起作用?您甚至可以从示例输出中看到它。它们的成本都不超过2美元。如果你已经有了这样一个解决方案,你就没有必要用5英镑的入场费找到去博物馆的最短路径。我可以说你正在修改dijsktra来解决这个问题吗?那么,您有什么建议可以有效地为每个人找到这一点node@PratikKale建议正确使用优先级队列。队列中的最大条目数为n+2m
,每个条目都需要O(log(n+2m))
来插入和检索。这个稍微超线性的时间与读取文件的时间相当。@NicoSchertler这是对这个问题的回答<代码>去博物馆的费用[从博物馆]是站在博物馆外面去博物馆最便宜的路的费用。啊,我明白了cost\u to\u museum[i]
是从i
开始参观任何博物馆的费用。我原以为参观博物馆要花很多钱。因此我感到困惑。