簡體   English   中英

參觀博物館的最低費用

[英]Minimum cost to visit museum

我最近參加了招聘挑戰,看到了這個問題:

給定N個博物館的 map,給定入場費和連接它們的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

Output 格式:

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

Output:

1 2 2 1 2

在這里,從1號館開始,我們可以直接參觀1號館,入場費為1。從3號館開始,我們可以參觀4號館,門票為2。

我需要比從圖形的每個節點應用 dijsktra 更有效的優化方法。 約束非常高,可以避免弗洛伊德 Warshall 算法。

提前致謝。

您的圖表以“X 博物館外”的節點和它們之間的邊緣道路開始。

您需要一個如下所示的條目優先級隊列:

{
    cost: xxx,
    outside_museum: xxx
}

您使用如下所示的條目對其進行初始化:

{
    cost: entry_fee_for_museum_x,
    outside_museum: x
}

保持一個字典映射博物館到最低成本,命名為cost_to_museum

現在你的循環看起來像這樣:

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是道路的數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM