image.png

  • input
6 8 0
0 1 1
0 3 4
0 4 4
1 3 2
2 5 1
3 2 2
3 4 3
4 5 3
  • output
0 1 5 3 4 6

邻接矩阵实现

#pragma warning (disable:4996)
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const int maxn = 1000;

const int INF = 0x3f3f3f3f;

int G[maxn][maxn], d[maxn];
bool vis[maxn] = { false };
int n, m, s;

void Dijkstra(int s)
{
    fill(d, d + maxn, sizeof d);
    d[s] = 0;
    //使d[u]最小的u
    for (int i = 0; i < n; i++)
    {
        int u = -1, MIN = INF;
        for (int j = 0; j < n; j++)
        {
            if (vis[j] == false && d[j] < MIN)
            {
                u = j;
                MIN = d[j];
            }
        }

        if (u == -1)
        {
            return;
        }
        vis[u] = true;
        //优化路径
        for (int v = 0; v < n; v++)
        {
            if (vis[v] == false && G[u][v] != INF)
            {
                if (d[u] + G[u][v] < d[v])
                {
                    d[v] = d[u] + G[u][v];
                }
            }
        }
    }
}


int main()
{
    freopen("test.txt", "r", stdin);
    int u, v, w;
    scanf("%d %d %d", &n, &m, &s);
    fill(G[0], G[0] + maxn * maxn, INF);
    for (int i = 0; i < m; i++)
    {
        scanf("%d %d %d", &u, &v, &w);
        G[u][v] = w;
    }

    Dijkstra(s);

    for (int i = 0; i < n; i++)
    {
        printf("%d ", d[i]);
    }

    return 0;
}

邻接表实现

#pragma warning(disable:4996)
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const int maxn = 1000;
const int INF = 0x3f3f3f3f;
int n, m, s;
int d[maxn];
bool vis[maxn];
struct Node
{
    int v;
    int w;
};
vector<Node> Adj[maxn];

void Dijkstra(int s)
{
    fill(d, d + maxn, sizeof d);
    d[s] = 0;
    for (int i = 0; i < n; i++)
    {
        int u = -1, MIN = INF;
        for (int j = 0; j < n; j++)
        {
            if (vis[j] == false && d[j] < MIN)
            {
                u = j;
                MIN = d[j];
            }
        }
        if (u == -1)
        {
            return;
        }
        vis[u] = true;
        for (int j = 0; j < Adj[u].size(); j++)
        {
            int v = Adj[u][j].v;
            if (vis[v] == false && d[u] + Adj[u][j].w < d[v])
            {
                d[v] = d[u] + Adj[ u][j].w;
            }
        }
    }
}

int main()
{
    //freopen("test.txt", "r", stdin);
    int u, v, w;
    scanf("%d %d %d", &n, &m, &s);
    Node temp;
    for (int i = 0; i < m; i++)
    {
        scanf("%d %d %d", &u, &v, &w);
        temp.v = v;
        temp.w = w;
        Adj[u].push_back(temp);
    }

    Dijkstra(s);

    for (int i = 0; i < n; i++)
    {
        printf("%d ", d[i]);
    }

    return 0;
}
参考资料《算法笔记》.

雨天
0 声望3 粉丝

独自灿烂