最短路:spfa算法

最短路:spfa算法

题目描述

参考代码

输入示例

3 3
1 2 5
2 3 -3
1 3 4

输出示例

2
cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 1e5 + 10;

int n, m;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool st[N];

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

int spfa()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    
    queue<int> q;
    q.push(1);
    st[1] = true;
    
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        
        st[t] = false;
        
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }
    
    if (dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    
    while (m -- )
    {
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        add(x, y, z);
    }
    
    int t = spfa();
    
    if (t == -1) printf("impossible\n");
    else printf("%d\n", t);
    
    return 0;
}
相关推荐
这可就有点麻烦了8 分钟前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊14 分钟前
顺序表及其代码实现
数据结构·算法
lin zaixi()17 分钟前
贪心思想之——最大子段和问题
数据结构·算法
FindYou.18 分钟前
C - Separated Lunch
算法·深度优先
夜雨翦春韭23 分钟前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
Kent_J_Truman35 分钟前
【平方差 / C】
算法
一直学习永不止步36 分钟前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
Amor风信子1 小时前
华为OD机试真题---跳房子II
java·数据结构·算法
戊子仲秋1 小时前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展
邓校长的编程课堂1 小时前
助力信息学奥赛-VisuAlgo:提升编程与算法学习的可视化工具
学习·算法