最短路之朴素版的dij板子

模板:

注意这个只是单向的双向的需要在更新一次

cpp 复制代码
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int, int>PII;
const int N=2e5+10;
const int MOD = 998244353;
const int INF=0X3F3F3F3F;
const int dx[]={-1,1,0,0,-1,-1,+1,+1};
const int dy[]={0,0,-1,1,-1,+1,-1,+1};
const int M = 1e6 + 10;

//好累啊
//朴素版的迪杰斯特拉算法

int n, m;
int g[2010][2010];
int dis[N];
bool st[N];

int dij()
{
	memset(dis, 0x3f, sizeof dis);
	dis[1] = 0;
	for(int i = 0; i < n; i ++)
	{
		int t = -1;
		for(int j = 1; j <= n; j ++)
		{
			if(!st[j] && (t == -1 || dis[t] > dis[j])) t = j;//找到下一个最短的来进行更新
		}
		st[t]  = true;//标记一下已经走过了
		for(int j = 1; j <= n; j ++)
		{
			dis[j] = min(dis[t] + g[t][j], dis[j]);//从那个最短端点依次更新
		}
	}
	if(dis[n] == 0x3f3f3f3f) return -1;
	return dis[n];
}
int main()
{
	cin >> n >> m;
	memset(g, 0x3f, sizeof g);
	while(m --){
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		g[a][b] = min(g[a][b], c);
	}
	cout << dij() << endl;
	return 0;
}
相关推荐
上班摸鱼下班游戏1 分钟前
Unity 仿生智能算法 从蚁群算法 开始
算法·unity·游戏引擎
pipixia2003312 分钟前
C++ 面试高频:namespace 的 6 个知识点,从 using 到匿名命名空间
c语言·学习·算法·嵌入式·命名空间·c++面试·匿名命名空间
Navigator_Z1 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
SZYSK1 小时前
鸿蒙人脸识别算法放在终端里:和外挂授权 SDK 差在排障路径
物联网·算法·华为·harmonyos
凯瑟琳.奥古斯特2 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
xiangyun612 小时前
C++ priority_queue 底层:手撕二叉堆与 Top K 问题
c++·算法·面试·stl·1024程序员节
qz_Serene3 小时前
练习算法题:双指针 -cpp
c++·算法·leetcode·1024程序员节
Nuanyt4 小时前
Hot 100 刷题笔记 · 数组与哈希专题(3 题)
java·笔记·算法·leetcode·哈希算法·1024程序员节
碧海银沙音频科技研究院4 小时前
基于炬芯平台ATS308X多模型兼容语音识别算法
人工智能·算法·语音识别
爱读书的小胖4 小时前
LeetCode 274 H 指数 C 语言解题分析
c语言·算法·leetcode·1024程序员节