寻找间接列车连接
Find indirect train connections
我必须找到两个给定城市代码之间的火车旅程,如果没有直接路线,那么我应该通过其他旅程找到间接路线。如果我想从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_path
、find_all_paths
和find_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.
相关文章:
- 当套接字连接断开时检测C/C++Unix
- 无法在windows上使用mingw将sqlite3与c连接
- 到连接组件算法的问题(递归)
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- 无法在C++中建立与MySQL数据库的连接
- PC中的程序和PHONE中的本机描述应用程序之间的数据连接
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 连接 dockerized 模型和 dockerized 数据库时出现"无法 SQLConnect"错误
- 使用 bfs 解决连接组件问题时得到错误的答案
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 如何修复valgrind启动时的致命错误(与libc6-dbg和libc6-dbg:i386连接)
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- OSX蓝牙打开RFCOMMChannelAsync声称已连接,但未建立连接,并且从未调用过委托
- 在 libcurl 连接池中预创建连接
- 套接字连接"Operation not permitted"错误,甚至使用升压/平发器根.cpp
- libcurl 和 DNS ttl 中的内部连接管理
- 如何应用 libcurl 的持久连接选项
- 提升 ASIO - io_service 不要等待连接到线程
- WinSock2:connect() 提供"连接被拒绝"
- 寻找间接列车连接