华为笔试题:地铁换乘问题
2016-08-27 09:55
274 查看
用了数据结构中的最短路径算法:
#include<iostream> #include<string> #include<stack> #define inf 1000 //定义无穷远距离 #define stanum 35 //定义总站台数 using namespace std; string s1[stanum] = { "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11", "B12", "B13", "B14", "B15", "T1", "T2" }; //记录车站的名字 void floyd(int dis[][stanum], int path[][stanum]) { //初始化path矩阵 for (int row = 0; row<stanum; row++) for (int col = 0; col<stanum; col++) path[row][col] = row; //找最短路径 for (int k = 0; k<stanum; k++) for (int i = 0; i<stanum; i++) for (int j = 0; j<stanum; j++) if (dis[i][j]>dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; path[i][j] = path[k][j]; } } int string2int(string s) //转换车站的名字到矩阵的索引 { for (int i = 0; i<stanum; i++) if (s == s1[i]) { return i; break; } } void printres(int dis[][stanum], int path[][stanum], string start, string dest) { cout << "start station to destination distance path" << endl; cout << "\t" << start << "->" << dest << "\t\t"; int s; int d; s = string2int(start); d = string2int(dest); cout << "\t" << dis[s][d] + 1 << "\t"; //输出站树加1包括了起始站 for (int i = 0; i<stanum; i++) for (int j = 0; j<stanum; j++) { if (i == s&&j == d) //输出路径 { stack<int> pathrout; //压栈 int k = j; do { k = path[i][k]; pathrout.push(k); } while (k != i); //弹栈 cout << s1[pathrout.top()]; pathrout.pop(); int length = pathrout.size(); for (int t = 0; t<length; t++) { cout << "->" << s1[pathrout.top()]; pathrout.pop(); } cout << "->" << s1[d] << endl; break; } } } int main() { int distance[stanum][stanum]; int path[stanum][stanum]; string start; string dest; //初始化连接矩阵 for (int i = 0; i<stanum; i++) { for (int j = 0; j<stanum; j++) { if (i == j) distance[i][j] = 0; else distance[i][j] = inf; } } //初始化技巧 int sa[21] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 33, 9, 10, 11, 12, 34, 13, 14, 15, 16, 17, 0 }; for (int i = 0; i<20; i++) { distance[sa[i]][sa[i + 1]] = 1; distance[sa[i + 1]][sa[i]] = 1; } int sb[17] = { 18, 19, 20, 21, 22, 33, 23, 24, 25, 26, 27, 34, 28, 29, 30, 31, 32 }; for (int i = 0; i<16; i++) { distance[sb[i]][sb[i + 1]] = 1; distance[sb[i + 1]][sb[i]] = 1; } floyd(distance, path); cout << "input start and destination" << endl; cin >> start >> dest; printres(distance, path, start, dest); system("pause"); return 0; }
相关文章推荐
- 华为机试--地铁换乘问题
- 华为机试 地铁换乘问题(最短路径算法)
- 华为笔试题——地铁换乘
- 华为地铁换乘问题
- 地铁换乘-最短路径问题
- 华为机试样题解析:已知2条地铁线路,其中A为环线,B为东西向线路,线路都是双向的。经过的站点名分别如下,两条线交叉的换乘点用T1、T2表示。 编写程序,任意输入两个站点名称,输出最少需要经过的站点数
- 2014华为机试——地铁换乘寻找最少车站数和排序算法
- 地铁换乘—华为2014校招机试样题 —Dijkstra 和 Floyd-Warshall 算法解决
- 华为机试题(地铁换乘,图的应用)
- 华为机试-地铁换乘
- 华为地铁换乘 Java
- 蓝桥杯地铁换乘问题
- 华为笔试题:N进制求和计算问题
- 华为上机笔试原题+代码---------股票投资问题
- 华为机试地铁换乘C++实现(不容易啊)
- 2014华为机试——地铁换乘寻找最少车站数和排序算法
- 华为2014上机考试样题_高级题_地铁换乘最短路径_无向无权图+邻接表存储+BFS广度优先算法
- 蓝桥杯地铁换乘问题
- 华为机试题-地铁换乘
- 地铁换乘(华为机试样题)