0分求助
查看原帖
0分求助
548059
VastUniverse_Hory楼主2023/1/2 19:41

C++

#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
int cnt = 0, next[20000], head[1000000], n, m, s, dis[1000][1000];

struct edge_struct
{
    int next, to, w;
} edge[100000];

inline void add(int next, int to, int w)
{
    edge[++ cnt].next = head[next];
    edge[cnt].to = to;
    edge[cnt].w = w;
    head[next] = cnt;
}

void spfa(int s)
{
    bool visited[100000] = {};
    queue <int> q;
    memset(dis, 0x3f, sizeof dis), q.push(s), dis[s][s] = 0, visited[s] = true;
    while (! q.empty())
    {
        int t = q.front();
        q.pop(), visited[t] = false;
        for (int i = head[t]; i; i = edge[i].next)
        {
            int v = edge[i].to;
            if (dis[s][v] > dis[s][t] + edge[i].w);
            {
                dis[s][v] = dis[s][t] + edge[i].w;
                if (! visited[v])
                    q.push(v), visited[v] = true;
            }
        }
    }
}

int main()
{
    ios :: sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> s;
    for (int i = 1; i <= m; i ++)
    {
        int u, v, w;
        cin >> u >> v >> w;
        add(u, v, w);
    }
    spfa(s);
    for (int i = 1; i <= n; i ++)
        cout << dis[s][i] << " ";
    cout << endl;
    return 0;
}
2023/1/2 19:41
加载中...