大二带专生


私信TA

用户名:dotcpp0676254

访问量:343

签 名:

等  级
排  名 8772
经  验 1147
参赛次数 0
文章发表 18
年  龄 0
在职情况 学生
学  校 职业技术学院
专  业

  自我简介:

解题思路:

注意事项:堆优化更好,不过本题不使用对优化的原因是本题直接给邻接矩阵,方便



参考代码:

#include <iostream>

#include <algorithm>

#include <cstring>

using namespace std;


const int N = 510, inf = 1e9 + 10;


int n, s;

int g[N][N], dist[N];

bool st[N];


void dijkstra()

{

    memset(dist, 0x3f, sizeof dist);

    dist[s] = 0;


    for (int i = 0; i < n; i++)

    {

        int t = -1;

        for (int j = 0; j <n; j++)

            if (!st[j] && (t == -1 || dist[t] > dist[j]))

                t = j;

        st[t] = true;


        for (int j = 0; j <n; j++)

            dist[j] = min(dist[j], dist[t] + g[t][j]);

    }

}


int main()

{

    cin >> n >> s;

    memset(g, 0x3f, sizeof g);

    for (int i =0; i < n; i++)

    {

        for (int j = 0; j < n; j++)

        {

            cin >> g[i][j];

            if (g[i][j] == 0 && i != j)

                g[i][j] = inf;

        }

    }

    dijkstra();

    for (int i = 0; i <n; i++)

    {

        if (i != s)

        {

            if (dist[i] >inf/2)

                cout << "-1 ";

            else

                cout << dist[i] << " ";

        }

    }

    puts("");


    return 0;

}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区