最短路: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;
}
相关推荐
明志数科10 分钟前
人类视频与机器人示教的数据配比:分层训练的数据采购与采集设计
人工智能·算法
Ivanqhz21 分钟前
MoE 原理、TC/EC 路由、LSH-MoE 与负载均衡浅析
运维·网络·人工智能·深度学习·算法·机器学习·负载均衡
Sarvartha24 分钟前
栈的四则运算、栈的递归应用
数据结构·算法
stolentime30 分钟前
CF2277E Tree Guessing题解
c++·算法·贪心算法·交互·ad-hoc
逐光者9331 小时前
杨氏模量:从定义到工程应用
算法
荆棘鸟智能2 小时前
扬尘在线监测数据接入与异常清洗:从断点补传到质量审计
人工智能·算法·系统架构
动词ing2 小时前
【题目练习】旋转图像
算法
天疆说2 小时前
【无标题】
算法
GG.WinGel3 小时前
三元组中心问题
java·数据结构·算法·青少年编程·蓝桥杯
开开心心就好3 小时前
电脑小说阅读器,支持朗读和自定义皮肤
服务器·开发语言·javascript·算法·pdf·c#·音视频