实验名称
校园地图导航
一、实验内容
写一个校园地图导航,可以在代码里设置好点名,路径,路径权重
程序运行,输入两个点,输出最短距离及最短路径
二、实现
#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);
}