简体   繁体   English

参观博物馆的最低费用

[英]Minimum cost to visit museum

I recently went for an hiring challenge and saw this question:我最近参加了招聘挑战,看到了这个问题:

Given map of N museums with given entry fees and M weighted bidirectional roads connecting them.给定N个博物馆的 map,给定入场费和连接它们的M个加权双向道路。 Starting from each museum, we need to find minimum cost to visit at least one museum.从每个博物馆开始,我们需要找到至少参观一个博物馆的最低成本。 The cost will be an addition of sum of weights of roads travelled and visited museum entry fee.费用将是经过的道路权重和参观博物馆入场费的总和。

Input format:输入格式:

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

Output Format: Output 格式:

N integers where ith integer denotes minimum cost to reach and enter any museum starting from ith museum.

Input:输入:

5 4 
1 2 3 1 5
1 2 1
2 3 1
3 4 1
4 5 1

Output: Output:

1 2 2 1 2

Here, starting from museum 1, we can directly visit museum 1 with entry fee of 1. Starting from museum 3, we can visit museum 4 with cost of 2.在这里,从1号馆开始,我们可以直接参观1号馆,入场费为1。从3号馆开始,我们可以参观4号馆,门票为2。

I need optimized approach efficient than applying dijsktra from each node of graph.我需要比从图形的每个节点应用 dijsktra 更有效的优化方法。 Constraints are high enogh to avoid floyd warshall algorithm.约束非常高,可以避免弗洛伊德 Warshall 算法。

Thanks in advance.提前致谢。

Your graph starts off with nodes of "outside Museum X" and edges roads between them.您的图表以“X 博物馆外”的节点和它们之间的边缘道路开始。

You need a priority queue of entries that look like this:您需要一个如下所示的条目优先级队列:

{
    cost: xxx,
    outside_museum: xxx
}

You initialize it with entries that look like this:您使用如下所示的条目对其进行初始化:

{
    cost: entry_fee_for_museum_x,
    outside_museum: x
}

Keep a dictionary mapping museum to lowest cost named something like cost_to_museum .保持一个字典映射博物馆到最低成本,命名为cost_to_museum

And now your loop looks like this:现在你的循环看起来像这样:

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)

This should execute in time O((n+m) log(n+m)) where n is the number of museums and m is the number of roads.这应该在O((n+m) log(n+m))时间内执行,其中n是博物馆的数量, m是道路的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM