#include <iostream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <fstream>
using namespace std;
const int maxn = 100;
int Hash(string s, string h[], int &num, int Match[])
{
int now = 0;
for (int i = 0; ; i++) {
now = (s[0] - 'A' + i) % maxn;
if (h[now] == "") {//如果没有被Hash过,就新建
h[now] = s;
Match[num] = now;
num++;
return now;
} else if (h[now] == s) {//如果被Hash过,就直接返回原来Hash出来的地址
return now;
}
}
}
void Floyd()
{
}
int main()
{
ifstream in("in.txt");
for (int i = 0; i < 4; i++) {
string s;
in >> s;
}
string h[maxn] = "";
string s1, s2;
int path[maxn][maxn];
for (int i = 0; i < maxn; i++) {
for (int j = 0; j < maxn; j++) {
path[i][j] = -1;
}
}
int cost, dis;
int cnt = 0;
int num = 0;
int Match[maxn];
while (in >> s1 >> s2 >> cost >> dis) {
cnt++;
int u = Hash (s1, h, num, Match);
int v = Hash (s2, h, num, Match);
path[u][v] = dis;
path[v][u] = dis;
}
in.close();
for (int k = 0; k <= num; k++) {
for (int i = 0; i <= num; i++) {
for (int j = 0; j <= num; j++) {
int a1 = Match[k], a2 = Match[i], a3 = Match[j];
if ((path[a2][a1] != -1 && path[a1][a3] != -1) && (path[a2][a1] + path[a1][a3] < path[a2][a3] || path[a2][a3] == -1)) {
path[a2][a3] = path[a2][a1] + path[a1][a3];
}
}
}
}
int op;
while (1) {
cout << "如果想继续得到城市间的最短距离,请输入1,如果想要退出程序,请输入0" << endl;
cin >> op;
if (op == 0) break;
cout << "请输入想要得到最短路的两个城市的名称,用空格隔开(请保证这两个城市的名称和文件中文件的名称一样)" << endl;
cin >> s1 >> s2;
int i = Hash (s1, h, num, Match), j = Hash (s2, h, num, Match);
if (path[i][j] == -1) {
cout << "抱歉,这两个城市之间没有路径到达" << endl;
} else {
cout << "两个城市之间最短距离为:" << path[i][j] << endl;
}
}
return 0;
}
任意两个城市之间最短路(Floyd)
最新推荐文章于 2023-02-15 20:19:31 发布