西北工业大学数据结构noj4-3

4-3用弗洛伊德算法求赋权图的两点间的最短路径的长度

question

在这里插入图片描述

完整代码

// 用弗洛伊德算法求赋权图的两点间的最短路径的长度
#include <iostream>
#include <vector>
#define INF 10000 // 无穷大,表示两结点之间无边

struct Graph
{
    std::vector<int> vertex;
    std::vector<std::vector<int>> arcs;
    int vexnum = 0, arcnum = 0;
};

void CreateGraph(Graph &G);

void Floyd(Graph G, std::vector<std::vector<int>> &dist);

int main()
{
    Graph G;
    CreateGraph(G);

    std::vector<std::vector<int>> dist;
    Floyd(G, dist);

    int m, start, end;
    std::cin >> m;

    for (auto i = 0; i < m; ++i)
    {
        std::cin >> start >> end;
        std::cout << dist[start][end] << std::endl;
    }

    system("pause");
    return 0;
}

void CreateGraph(Graph &G)
{
    int n;
    std::cin >> n;
    G.vexnum = n;
    G.arcs.resize(n, std::vector<int>(n, 0));

    for (auto i = 0; i < G.vexnum; ++i)
    {
        for (auto j = 0; j < G.vexnum; ++j)
        {
            std::cin >> n;
            G.arcs[i][j] = n;
        }
    }
}

void Floyd(Graph G, std::vector<std::vector<int>> &dist)
{
    int n = G.vexnum;

    dist.resize(n, std::vector<int>(n, 0));

    for (auto i = 0; i < n; ++i)
    {
        for (auto j = 0; j < n; ++j)
        {
            dist[i][j] = G.arcs[i][j];
        }
    }

    for (auto i = 0; i < n; ++i)
    {
        for (auto start = 0; start < n; ++start)
        {
            for (auto end = 0; end < n; ++end)
            {
                if (dist[start][end] > dist[start][i] + dist[i][end])
                {
                    dist[start][end] = dist[start][i] + dist[i][end];
                }
            }
        }
    }
}

// 4
// 0 2 10 10000
// 2 0 7 3
// 10 7 0 6
// 10000 3 6 0
// 2
// 0 2
// 3 0

// 9
// 5


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值