洛谷 P4779 【模板】单源最短路径

该博客介绍了如何使用C++实现Dijkstra算法,解决带权重的图中从源点到其他节点的最短路径问题。通过`std`库和自定义数据结构,博主展示了如何构建图、添加边和权重,并详细解释了Dijkstra算法的工作原理和优先队列的使用。
摘要由CSDN通过智能技术生成
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;

const int N = 1e6 + 10;
int n, m, s;
int e[N], ne[N], hh[N], idx, we[N];
int d[N];  //存储最短路
bool f[N]; //表示最短路已经确定

void add(int x, int y, int z)
{
    e[idx] = y;
    we[idx] = z;
    ne[idx] = hh[x];
    hh[x] = idx++;
}

void dijkstra()
{
    memset(d, 0x3f3f3f3f, sizeof d);
    d[s] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> h;
    h.push({0, s}); //first 距离 second 点
    while (!h.empty())
    {
        auto t = h.top();
        h.pop();
        int dd = t.first, vv = t.second;

        if (f[vv])
            continue;
        f[vv] = 1;
        for (int i = hh[vv]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (d[j] > dd + we[i])
            {
                d[j] = dd + we[i];
                h.push({d[j], j});
            }
        }
    }
}

void run()
{
    int u, v, w;
    memset(hh, -1, sizeof hh);
    cin >> n >> m >> s;
    while (m--)
    { 
        cin >> u >> v >> w;
        add(u, v, w);
    }
    dijkstra();
    for(int i = 1; i <= n; i ++)
    {
        if(d[i] == 0x3f3f3f3f) cout << 2147483647 << " ";
        else cout << d[i] << " ";
    }
}
int main()
{
    freopen("in.in", "r", stdin);
    freopen("out.out", "w", stdout);
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    run();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值