One-way flight trip problem

后端 未结 18 1497

You are going on a one-way indirect flight trip that includes billions an unknown very large number of transfers.

  • You are not stoppi
18条回答
  •  悲&欢浪女
    2020-12-12 17:44

    Construct two hash tables (or tries), one keyed on src and the other on dst. Choose one ticket at random and look up its dst in the src-hash table. Repeat that process for the result until you hit the end (the final destination). Now look up its src in the dst-keyed hash table. Repeat the process for the result until you hit the beginning.

    Constructing the hash tables takes O(n) and constructing the list takes O(n), so the whole algorithm is O(n).

    EDIT: You only need to construct one hash table, actually. Let's say you construct the src-keyed hash table. Choose one ticket at random and like before, construct the list that leads to the final destination. Then choose another random ticket from the tickets that have not yet been added to the list. Follow its destination until you hit the ticket you initially started with. Repeat this process until you have constructed the entire list. It's still O(n) since worst case you choose the tickets in reverse order.

    Edit: got the table names swapped in my algorithm.

提交回复
热议问题