One-way flight trip problem

后端 未结 18 1503

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

    It seems to me like a graph-based approach is based here.

    Each airport is a node, each ticket is an edge. Let's make every edge undirected for now.

    In the first stage you are building the graph: for each ticket, you lookup the source and destination and build an edge between them.

    Now that the graph is constructed, we know that it is acyclical and that there is a single path through it. After all, you only have tickets for trips you took, and you never visited the same airport once.

    In the second stage, you are searching the graph: pick any node, and initiate a search in both directions until you find you cannot continue. These are your source and destination.

    If you need to specifically say which was source and which was destination, add a directory property to each edge (but keep it an undirected graph). Once you have the candidate source and destination, you can tell which is which based on the edge connected to them.

    The complexity of this algorithm would depend on the time it takes to lookup a particular node. If you could achieve an O(1), then the time should be linear. You have n tickets, so it takes you O(N) steps to build the graph, and then O(N) to search and O(N) to reconstruct the path. Still O(N). An adjacency matrix will give you that.

    If you can't spare the space, you could do a hash for the nodes, which would give you O(1) under optimal hashing and all that crap.

提交回复
热议问题