华为笔试题:地铁换乘问题

用了数据结构中的最短路径算法:

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值