简体   繁体   中英

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. 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:

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:

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.

I need optimized approach efficient than applying dijsktra from each node of graph. Constraints are high enogh to avoid floyd warshall algorithm.

Thanks in advance.

Your graph starts off with nodes of "outside Museum X" and edges roads between them.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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