首页 > 代码库 > 华为机试--地铁换乘
华为机试--地铁换乘
【问题】
描述:已知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
地铁线B(直线)经过车站:B1 B2 B3 B4 B5 T1 B6 B7 B8 B9 B10 T2 B11 B12 B13 B14 B15
地铁线A(环线)经过车站:A1 A2 A3 A4 A5 A6 A7 A8 A9 T1 A10 A11 A12 A13 T2 A14 A15 A16 A17 A18
地铁线B(直线)经过车站:B1 B2 B3 B4 B5 T1 B6 B7 B8 B9 B10 T2 B11 B12 B13 B14 B15
输入:输入两个不同的站名
输出:输出最少经过的站数,含输入的起点和终点,换乘站点只计算一次
输入样例:A1 A3
输出样例:3
【代码】
#include <stdio.h> #include <stdlib.h> #include <string.h> int jishi3(char *start, char *end) { int a1[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; //线路A到T1站的距离 int a2[] = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6}; //线路A到T2站的距离 int b1[] = {6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; //线路B到T1站的距离 int b2[] = {12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6}; //线路B到T2站的距离 //线路A char aa[20][5] = {"A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "T1", "A10", "A11", "A12", "A13", "T2", "A14", "A15", "A16", "A17", "A18"}; //线路B char bb[17][5] = {"B1", "B2", "B3", "B4", "B5", "T1", "B6", "B7", "B8", "B9", "B10", "T2", "B11", "B12", "B13", "B14", "B15"}; int count=0; int i; int tmp1, tmp2; int posS, posE; //起点终点都是换乘站 if (start[0] == 'T' && end[0] == 'T') count = 6; //起点终点都在线路A上 else if (start[0] != 'B' && end[0] != 'B') { for (i = 0; i < 20; i++) { if (strcmp(start, aa[i]) == 0) posS = i; if (strcmp(end, aa[i]) == 0) posE = i; } count = 1 + (((posS - posE) > 0) ? (posS - posE) : (posE - posS)); } //起点终点都在线路B上 else if (start[0] != 'A' && end[0] != 'A') { for (i = 0; i < 17; i++) { if (strcmp(start, bb[i]) == 0) posS = i; if (strcmp(end, bb[i]) == 0) posE = i; } count = 1 + (((posS - posE) > 0) ? (posS - posE) : (posE - posS)) ; } //起点终点在分别在两条线路上 else { //起点在线路A上,终点在线路B上 if (start[0] == 'A') { for (i = 0; i < 20; i++) if (strcmp(start, aa[i]) == 0) { posS = i; break; } for (i = 0; i < 17; i++) if (strcmp(end, bb[i]) == 0){ posE = i; break; } } //起点在线路B上,终点在线路A上 else { for (i = 0; i < 20; i++) if (strcmp(end, aa[i]) == 0) { posE = i; break; } for (i = 0; i < 17; i++) if (strcmp(start, bb[i]) == 0){ posS = i; break; } } tmp1 = a1[posS] + b1[posE]; tmp2 = a2[posS] + b2[posE]; count = ((tmp1 > tmp2)? tmp2 : tmp1) - 1; } return count; } int main(void) { char start[10], end[10]; int count; scanf("%s", start); scanf("%s", end); count = jishi3(start, end); printf("%d\n", count); return 0; }
华为机试--地铁换乘
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。