任意两个城市之间最短路(Floyd)

#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;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值