最短路: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;
}
相关推荐
0 0 0几秒前
CCF-CSP 36-2 梦境巡查(dream)【C++】考点:前缀和
开发语言·c++·算法
VALENIAN瓦伦尼安教学设备几秒前
便携式蒸汽阀门漏气检测仪作用
人工智能·嵌入式硬件·算法
plus4s2 分钟前
3月11日(进阶3)
算法
We་ct6 分钟前
LeetCode 39. 组合总和:DFS回溯解法详解
前端·算法·leetcode·typescript·深度优先·个人开发·回溯
小杍随笔7 分钟前
【Rust中所有符号的作用及使用场景详解】
java·算法·rust
MicroTech202512 分钟前
微算法科技(NASDAQ: MLGO)探索量子机器学习算法在预测模型中的应用,利用量子核方法提升复杂模式识别能力
科技·算法·机器学习
absunique1 小时前
算法设计模式看编程思维的抽象能力的技术6
算法·设计模式
DeepModel2 小时前
【概率分布】Beta分布详解
算法·概率论
我命由我123452 小时前
React - 验证 Diffing 算法、key 的作用
javascript·算法·react.js·前端框架·html·html5·js
Eward-an6 小时前
LeetCode 1980 题通关指南|3种解法拆解“找唯一未出现二进制串”问题,附Python最优解实现
python·算法·leetcode