高级题样题:地铁换乘
描述:已知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
输入:输入两个不同的站名
输出:输出最少经过的站数,含输入的起点和终点,换乘站点只计算一次
输入样例:A1 A3
输出样例:3
#include<iostream> #include<algorithm> #include<string> #include<vector> using namespace std; int getRide(string pointA, string pointB) { string AA[20]={"A1","A2","A3","A4","A5","A6","A7","A8","A9","T1","A10","A11","A12","A13","T2","A14","A15","A16","A17","A18"}; vector<string> A(AA,AA+20); string BB[17]={"B1","B2","B3","B4","B5","T1","B6","B7","B8","B9","B10","T2","B11","B12","B13","B14","B15"}; vector<string> B(BB,BB+17); int num1=1,num2 = 1;//顺向走向的站数num1,逆向走向的站数num2; int start;//起点的编号 if((pointA[0]==‘A‘&&pointB[0]==‘A‘)||(pointA[0]==‘A‘&&pointB[0]==‘T‘)||(pointA[0]==‘T‘&&pointB[0]==‘A‘))//环形 { int i = 0; while(A[i]!=pointA && i<20) i++; start = i; int j = start;//向前走的编号j while(A[j]!=pointB) { num1++; j++; if(j>=20) j -= 20; } int m = start;//向后走的编号j while(A[m]!=pointB) { num2++; m--; if(m<0) m += 20; } if(num1<num2) return num1; else return num2; } else if((pointA[0]==‘B‘&&pointB[0]==‘B‘)||(pointA[0]==‘T‘&&pointB[0]==‘B‘)||(pointA[0]==‘B‘&&pointB[0]==‘T‘)) { num1 = 1; num2 = 1; int i = 0,a=0; int end; while(B[i]!=pointA && i<17) i++; start = i; while(B[i]!=pointB && i<17) a++; end = a; if(start>end) { int temp = start; start = end; end = temp; } if(start<=5 && end>=11) return end-start; else return end-start+1; } else if((pointA[0]==‘A‘&&pointB[0]==‘B‘) || (pointA[0]==‘B‘&&pointB[0]==‘A‘)) { if(pointA[0]==‘B‘) { string temp = pointA; pointA = pointB; pointB = temp; } int i = 0; while(B[i]!=pointB && i<17) i++; start = i; //B分别遇到T1、T2后选择A线路顺着或者逆着走,共有4个答案; vector<int> res(4,0); // 分别记录T1顺时针、T1逆时针、T2顺时针、T2逆时针 if(i<5)//到T1、T2的初始值的计算 { res[0] = 5 - start+1; res[1]=res[0]; res[2] = 11 - start+1; res[3]=res[2]; } else if(i>5 && i<11) { res[0] = start-5+1; res[1]=res[0]; res[2] = 11 - start+1; res[3]=res[2]; } else { res[0] = start-5+1; res[1]=res[0]; res[2] = start-11+1; res[3]=res[2]; }//初始值计算完毕 //T1到A1的顺时针距离 int j0 = 9;//向前走的编号j0 while(A[j0]!=pointA) { res[0]++; j0++; if(j0>=20) j0 -= 20; } //T1到A1的逆时针距离 int j1 = 9; while(A[j1]!=pointA) { res[1]++; j1--; if(j1<0) j1 += 20; } //T2到A1的逆时针距离 int j2 = 14;//向前走的编号j0 while(A[j2]!=pointA) { res[2]++; j2++; if(j2>=20) j2 -= 20; } //T2到A1的顺时针距离 int j3 = 14; while(A[j3]!=pointA) { res[3]++; j3--; if(j3<0) j3 += 20; } sort(res.begin(),res.end()); return res[0]; } else if((pointA=="T1"&&pointB=="T2") ||(pointA=="T2"&&pointB=="T1")) return 6; } void main() { string A="T2"; string B="T1"; int n = getRide(A,B); cout<<n<<endl; }
要把各种情况都考虑到,开始写时把框架先写好,然后往框架中填代码,写一部分测试一部分,如果有拷贝的代码,写时一定要仔细检查确保变量正确无误,否则浪费时间调试。
思路清晰,情况考虑全,就这两点!
原文地址:http://www.cnblogs.com/Xylophone/p/3819513.html