当前位置: 首页 > news >正文

最短路:spfa算法

最短路:spfa算法

    • 题目描述
    • 参考代码![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/3be484da34a84911a0a7dab3f1d84945.png)

题目描述

参考代码在这里插入图片描述

输入示例

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

输出示例

2
#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;
}
http://www.lryc.cn/news/370314.html

相关文章:

  • 算法笔记 图论和优先级队列的笔记
  • 6.每日LeetCode-数组类,找到所有数组中消失的数字
  • 【Three.js】知识梳理十:Three.js纹理贴图
  • mysql order by后跟case when
  • 数字孪生赋能的智慧园区物联网云平台建设方案(97页PPT)
  • TikTok小店运营策略
  • Docker面试整理-如何查看和管理Docker容器的日志?
  • Java从放弃到继续放弃
  • 上传文件生成聊天机器人,实现客服、办公自动化智能体 | Chatopera
  • SD3303A 大功率高亮度LED驱动芯片IC
  • 站易WordPress
  • windows下JDK1.8安装
  • 怎么修改Visual Studio Code中现在github账号
  • 戴尔R720服务器(3)组RAID
  • eNSP学习——配置高级的访问控制列表
  • oracle的bitmap索引是什么
  • 「前端+鸿蒙」鸿蒙应用开发-TS接口-特殊用途
  • Centos7系统禁用Nouveau内核驱动程序【笔记】
  • Vue 面试通杀秘籍
  • 聚焦新版综合编程能力面试考查汇总
  • [工具探索]英寸vs毫米下常见尺寸排版
  • Mimio安装
  • RawChat:优化AI对话体验,全面兼容GPT功能平台
  • 一文详解PaaS平台:机遇、挑战与新变革
  • Go每日一库之rotatelogs
  • 我的网络安全之路——一场诗意的邂逅
  • Android 中USB-HID协议实现
  • 学习AI 机器学习,深度学习需要用到的python库
  • 计算机网络 期末复习(谢希仁版本)第8章
  • abap 多线程运行demo