华为机试题——高级题:地铁换乘

来源:互联网 发布:淘宝直通车关键词策略 编辑:程序博客网 时间:2024/04/29 08:51
已知2条地铁线路,其中A为环线,B为东西向线路,线路都是双向的。经过的站点名分别如下,两条线交叉的换乘点用T1、T2表示。编写程序,任意输入两个站点名称,输出乘坐地铁最少需要经过的车站数量(含输入的起点和终点,换乘站点只计算一次)。
地铁线A(环线)经过车站:a1 a2 a3 a4 a5 a6 a7 a8 a9 t1 a10 a11 a12 a13 t2 a14 a15 a16 a17 a18

地铁线A(直线)经过车站:b1 b2 b3 b4 b5 b1 b6 b7 b8 b9 b10 t2 b11 b12 b13 b14 b15

 

#include<cstring>#include<iostream>#include<string>using namespace std;const int inf = 0x5F5F5F5F;struct Graph{char point[35][4];int edges[35][35];};char s1[21][4] = {"a1","a2","a3","a4","a5","a6","a7","a8","a9","t1","a10","a11","a12","a13","t2","a14","a15","a16","a17","a18","a1"};char s2[17][4] = {"b1","b2","b3","b4","b5","t1","b6","b7","b8","b9","b10","t2","b11","b12","b13","b14","b15"};char v[35][4] = {"a1","a2","a3","a4","a5","a6","a7","a8","a9","t1","a10","a11","a12","a13","t2","a14","a15","a16","a17","a18","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15"};//void *memcpy(void *dest, const void *src, size_t n);//需要#include<cstring>或#include<string.h>void CreateGraph(Graph * &G){int i,j,k;for(i=0;i<35;i++){memcpy(G->point[i],v[i],sizeof(v[i]));}for(i=0;i<35;i++){for(j=0;j<35;j++){G->edges[i][j] = inf;}}for(k=0;k<20;k++){for(i=0;strcmp(s1[k],G->point[i])!=0;i++);for(j=0;strcmp(s1[k+1],G->point[j])!=0;j++);G->edges[i][j] = 1;G->edges[j][i] = 1;}for(k=0;k<16;k++){for(i=0;strcmp(s2[k],G->point[i])!=0;i++);for(j=0;strcmp(s2[k+1],G->point[j])!=0;j++);G->edges[i][j] = 1;G->edges[j][i] = 1;}}//Floyd-Warshall算法的时间复杂度为O(N^3),空间复杂度为O(N^2)void Floyed(Graph * &G){int i,j,k;for(k=0;k<35;k++){for(i=0;i<35;i++){for(j=0;j<35;j++){if(G->edges[i][k]+G->edges[k][j]<G->edges[i][j])G->edges[i][j] = G->edges[i][k]+G->edges[k][j];}}}}void query(Graph *G)  {      char s1[4],s2[4];      int i,j;      cout<<"请输入起点站与终点站"<<endl;      cin>>s1>>s2;      for (i = 0;strcmp(s1,G->point[i])!=0;i++);                                  for (j = 0;strcmp(s2,G->point[j])!=0;j++);      cout<<G->edges[i][j]<<endl;  } int main(){Graph *G = new Graph;CreateGraph(G);Floyed(G);while(1){query(G);}system("pause");return 0;}


 

0 0