寻找间接列车连接

Find indirect train connections

本文关键字:连接 列车 寻找      更新时间:2023-10-16

我必须找到两个给定城市代码之间的火车旅程,如果没有直接路线,那么我应该通过其他旅程找到间接路线。如果我想从A到B,我可能需要从A到C再到B

我的火车路线文件的形式是:出发代码目的地代码公司价格时间这是两个城市代码之间的直达路线。

现在我已经使用了下面的循环进行直接连接,并且它工作了,我只需要帮助处理间接连接。

// load file data into v1
string dep, dest;
cout << "ntEnter the departure: ";
cin >> dep;
cout << "ntEnter the destination: ";
cin >> dest;
for(int i = 0; i < v1.size(); ++i) {
    // Departure() and Destination(), return the departure/destination codes
    if (v1[i].Departure() == dep && v1[i].Destination() == dest)
          // here I find all the direct routes
    else
         // indirect routes dealt with here
}

我认为对于间接路由,我必须在else部分处理它们。但是我很难看到我该怎么做,我想我必须看看第一个出发的目的地在哪里,并将它与我给定的dest匹配。

这是一个图表。

有许多方法可以找到一条路径,许多方法可以找到最短的路径,许多方法可以找到最便宜的路径。

这不是一个简单的else语句,但我建议你仔细阅读:

http://en.wikipedia.org/wiki/Dijkstra 's_algorithm

http://en.wikipedia.org/wiki/Shortest_path_problem

我建议你阅读下面的文章(它很短):

http://www.python.org/doc/essays/graphs.html

由Python编程语言的创建者Guido von Rossum编写。

我喜欢它,因为它讨论了如何使用字典实现图(用c++的说法是std::map),并提供了find_pathfind_all_pathsfind_shortest_path的非常简短、有效的实现。考虑到它们是用Python实现的,将它们翻译成c++是很简单的(因为Python易于阅读;将其视为伪代码而不是 (Python解决方案)。

例如,下面的代码实现了find_all_paths:

def find_all_paths(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return [path]
        if not graph.has_key(start):
            return []
        paths = []
        for node in graph[start]:
            if node not in path:
                newpaths = find_all_paths(graph, node, end, path)
                for newpath in newpaths:
                    paths.append(newpath)
        return paths

注意这是一个递归实现

你可以看看谷歌在谷歌地图上为谷歌交通做了什么:http://ad.informatik.uni-freiburg.de/files/transferpatterns.pdf.