洛谷P4779 【模板】单源最短路径(标准版) #最短路 Dijkstra算法 链式前向星 堆优化#

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_35850147/article/details/90477542

题目背景

2018 年 7 月 19 日,某位同学在 NOI Day 1 T1 归程 一题里非常熟练地使用了一个广为人知的算法求最短路。

然后呢?

100→60;

Ag→Cu;

最终,他因此没能与理想的大学达成契约。

小F衷心祝愿大家不再重蹈覆辙。

题目描述

给定一个N个点,M条有向边的带非负权图,请你计算从S出发,到每个点的距离。

数据保证你能从S出发到任意点。

输入输出格式

输入格式:

第一行为三个正整数N,M,S。第二行起M行,每行三个非负整数ui​,vi​,wi​,表示从ui到vi有一条权值为wi​的边。

输出格式:

输出一行N个空格分隔的非负整数,表示S到每个点的距离。

输入输出样例

输入样例#1: 复制

4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4

输出样例#1: 复制

0 2 4 3

说明

样例解释请参考 数据随机的模板题

1≤N≤100000;

1≤M≤200000;

S=1;

1≤ui​,vi​≤N;

0≤wi​≤10e9,

0≤∑wi​≤10e9。

本题数据可能会持续更新,但不会重测,望周知。

2018.09.04 数据更新 from @zzq

题解

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e5 + 10;
const int maxm = 2e5 + 10;
bool vis[maxn];
int n, m, s, cnt, head[maxn], dis[maxn];
struct edge { int v, w, next; } e[maxm];
struct node
{
    int u, w;
    bool operator < (const node &n) const { return w > n.w; }
};
priority_queue<node> q;

inline const int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
    return x * f;
}

void addedge(int u, int v, int w)
{
    e[cnt].v = v;
    e[cnt].w = w;
    e[cnt].next = head[u];
    head[u] = cnt++;
}

void dijkstra(int src)
{
    memset(dis, 0x3f, sizeof(dis));
    dis[src] = 0;
    q.push(node{src, 0});
    while (!q.empty())
    {
        int u = q.top().u; q.pop();
        if (vis[u]) continue;
        vis[u] = true;
        for (int i = head[u]; ~i; i = e[i].next)
        {
            int v = e[i].v, w = e[i].w;
            if (dis[v] > dis[u] + w)
            {
                dis[v] = dis[u] + w;
                q.push(node{v, dis[v]});
            }
        }
    }
}

int main()
{
    n = read(); m = read(); s = read();
    memset(head, -1, sizeof(head));
    while (m--)
    {
        int u = read(), v = read(), w = read();
        addedge(u, v, w);
    }
    dijkstra(s);
    for (int i = 1; i <= n; i++) printf("%d%s", dis[i], i == n ? "\n" : " ");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35850147/article/details/90477542