算法训练 最短路

这篇博客介绍了如何利用SPFA(Shortest Path Faster Algorithm)算法解决含有负权边的有向图中,从起点1到其他所有点的最短路径问题。代码实现中,首先定义了图的结构和辅助函数,然后通过SPFA模板进行单起点最短路径计算,并输出结果。该算法适用于稀疏图,并能有效避免负权环导致的无限循环问题。
摘要由CSDN通过智能技术生成

问题描述
给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。

输入格式
第一行两个整数n, m。

接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。

输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。

样例输入
3 3
1 2 -1
2 3 -1
3 1 2
样例输出
-1
-2
数据规模与约定
对于10%的数据,n = 2,m = 2。
对于30%的数据,n <= 5,m <= 10。
对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。

spfa

思路:单起点,稀疏图,负权边,套spfa模板。

#include <iostream>
#include <queue>
#include <cstring>

const int N = 20010, M = 2000010;
using namespace std;
int n, m;
int h[N], e[N], ne[N], w[N], cur;
int dis[N];
bool st[N];

void add(int a, int b, int c)
{
    e[cur] = b;
    w[cur] = c;
    ne[cur] = h[a];
    h[a] = cur ++;
}

void spfa()
{
    memset(dis, 0x3f, sizeof dis);
    dis[1] = 0;
    queue<int> q;
    q.push(1);
    st[1] = true;

    while(q.size())
    {
        int t = q.front();
        q.pop();
        st[1] = false;

        for(int i = h[t]; i != -1 ; i = ne[i]){
            int j = e[i];
            if(dis[j] > dis[t] + w[i]){
                dis[j] = dis[t] + w[i];
                if(!st[j]){
                    q.push(j);
                    st[j] = true;
                }   
            }
        }
    }
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);

    while(m --)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }

    spfa();

    for(int i = 2; i <= n ; i ++)
    {
        cout << dis[i] << endl;
    }

    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值