洛谷 P4779 【模板】单源最短路径(标准版)

洛谷 P4779 【模板】单源最短路径(标准版)

Description

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

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

    1≤N≤100000;

    1≤M≤200000;

    S=1

    1≤ui,vi≤N

    0≤wi≤10的9次方

    0≤∑wi≤10的9次方

Input

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

Output

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

Sample Input

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

Sample Output

0 2 4 3

题解:

  • 一道dijskra的板子题。我居然拖了一年才学… …
  • 挺简单的。朴素dijskra的过程如下:
    1. 初始化dis[start]=0,其余节点的dis值为无穷大.
    2. 找一个dis值最小的蓝点x,把节点x变成白点.
    3. 遍历x的所有出边(x,y,z)若dis[y]>dis[x]+z, 则令dis[y]=dis[x]+z
    4. 重复2,3两步,直到所有点都成为白点...
  • 时间是O(n方)的,主要问题出在第2步上。所以这时用一个堆维护最小值就行了
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define N 100005
#define M 200005
using namespace std;

struct Node
{
    int val, pos;
    friend bool operator<(Node x, Node y) {
        return x.val > y.val;
    }
};
struct E {int next, to, dis;} e[M];
int n, m, s, num;
int h[N], dis[N];
bool vis[N];

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

void add(int u, int v, int w)
{
    e[++num].next = h[u];
    e[num].to = v;
    e[num].dis = w;
    h[u] = num;
}

void dijskra()
{
    priority_queue<Node> que;
    memset(dis, 0x3f, sizeof(dis));
    dis[s] = 0, que.push((Node){0, s});
    while(!que.empty())
    {
        int x = que.top().pos;
        que.pop();
        if(vis[x]) continue;
        vis[x] = 1;
        for(int i = h[x]; i != 0; i = e[i].next)
            if(dis[x] + e[i].dis < dis[e[i].to])
            {
                dis[e[i].to] = dis[x] + e[i].dis;
                if(!vis[e[i].to]) que.push((Node){dis[e[i].to], e[i].to});
            }
    }
}

int main()
{
    cin >> n >> m >> s;
    for(int i = 1; i <= m; i++)
    {
        int u = read(), v = read(), w = read();
        add(u, v, w);
    }
    dijskra();
    for(int i = 1; i <= n; i++) printf("%d ", dis[i]);
    return 0;
}

转载于:https://www.cnblogs.com/BigYellowDog/p/11216137.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值