最短路: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;
}
相关推荐
yugi9878387 分钟前
基于Takens嵌入定理和多种优化算法的混沌序列相空间重构MATLAB实现
算法·matlab·重构
Yuer202514 分钟前
为什么要用rust做算子执行引擎
人工智能·算法·数据挖掘·rust
持梦远方14 分钟前
持梦行文本编辑器(cmyfEdit):架构设计与十大核心功能实现详解
开发语言·数据结构·c++·算法·microsoft·visual studio
im_AMBER36 分钟前
Leetcode 90 最佳观光组合
数据结构·c++·笔记·学习·算法·leetcode
薛不痒36 分钟前
机器学习算法之SVM
算法·机器学习·支持向量机
AndrewHZ1 小时前
【复杂网络分析】如何入门Louvain算法?
python·算法·复杂网络·社区发现·community det·louvain算法·图挖掘
AndrewHZ1 小时前
【图像处理基石】如何基于黑白图片恢复出色彩?
图像处理·深度学习·算法·计算机视觉·cv·色彩恢复·deoldify
POLITE31 小时前
Leetcode 3.无重复字符的最长子串 JavaScript (Day 4)
javascript·算法·leetcode
Xの哲學1 小时前
Linux IPC机制深度剖析:从设计哲学到内核实现
linux·服务器·网络·算法·边缘计算
sin_hielo1 小时前
leetcode 756(枚举可填字母)
算法·leetcode