数据结构实验6:校园地图导航

实验名称

校园地图导航

一、实验内容

写一个校园地图导航,可以在代码里设置好点名,路径,路径权重

程序运行,输入两个点,输出最短距离及最短路径

二、实现

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

typedef pair<int, int> PII;
const int N = 1010;
int e[N], ne[N], h[N], w[N], idx;
int dist[N];
bool st[N];
int fa[N];
vector<int> num;

void add(int a, int b, int c)
{
	e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

string readFileIntoString(char *filename)
{
	ifstream ifile(filename); //将文件读入到ostringstream对象buf中
	ostringstream buf;
	char ch;
	while (buf && ifile.get(ch))
		buf.put(ch); //返回与流对象buf关联的字符串
	return buf.str();
}

void read()
{
	char a = ' ';
	fstream f("data.txt");
	string s;
	string line;
	while (getline(f, line))//会自动把换行符去掉
	{
		s = s + line + ' ';
	}
	
	for (int i = 0; i < s.size();i++)
	{
		int sum = 0;
		while (s[i] != ' ')
		{
			sum = sum * 10 + s[i]-48;
			i++;
		}
		num.push_back(sum);
	}
}

void CreatMap()
{
	memset(h, -1, sizeof h);
	read();
	for (int i = 0; i < num.size(); i += 3)
	{
		int a = num[i], b = num[i + 1], c = num[i + 2];
		add(a, b, c);
		add(b, a, c);
	}
}

void dijkstra(int a)
{
	memset(fa, -1, sizeof fa);
	memset(dist, 0x3f, sizeof dist);
	dist[a] = 0;
	priority_queue<PII, vector<PII>, greater<PII>> smallheap;
	smallheap.push({ 0,a });
	while (smallheap.size())
	{
		auto t = smallheap.top();
		smallheap.pop();
		int ver = t.second, distance = t.first;

		if (st[ver]) continue;
		st[ver] = true;

		for (int i = h[ver]; i != -1; i=ne[i])
		{
			int j = e[i];
			if (dist[j] > dist[ver] + w[i])
			{
				dist[j] = dist[ver] + w[i];
				smallheap.push({ dist[j],j });
				fa[j] = ver;
			}
		}
	}
}

void PrintPath(int a, int b)
{
	if (dist[b] == 0x3f3f3f3f)
		cout << "non existent" << endl;
	else
	{
		cout <<"the distance of the shortest path is "<< dist[b] << endl;
		vector<int> path;
		do
		{
			path.push_back(b);
			b = fa[b];
		} while (fa[b] != -1);
		reverse(path.begin(), path.end());

		cout << a << " -> ";
		for (int i = 0; i < path.size() - 1; i++)
			cout << path[i] << " -> ";
		cout << path[path.size() - 1];
	}
}

int main()
{
	CreatMap();
	int start, end;
	cout << "1:操场  2:餐厅  3:四区  4:六区  5:五区  6:七区" << endl;
	cin >> start >> end;
	dijkstra(start);
	PrintPath(start, end);
}

  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值