最短路之朴素版的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;
}
相关推荐
生信研究猿6 分钟前
94. 二叉树的中序遍历 (二叉树遍历整理)
数据结构·算法
挂科边缘7 分钟前
image-restoration-sde复现,图像修复,使用均值回复随机微分方程进行图像修复,ICML 2023
算法·均值算法·ir-sde·扩散模块图像修复
2301_822703207 分钟前
开源鸿蒙跨平台Flutter开发:血氧饱和度数据降噪:基于滑动窗口的滤波算法优化-利用动态列队 (Queue) 与时间窗口平滑光电容积脉搏波 (PPG)
算法·flutter·华为·开源·harmonyos
Vin0sen8 分钟前
算法-线段树与树状数组
算法
sycmancia13 分钟前
QT——计算器核心算法
开发语言·qt·算法
倦王14 分钟前
力扣日刷45
算法·leetcode·职场和发展
炽烈小老头18 分钟前
【 每天学习一点算法 2026/04/06】常数时间插入、删除和获取随机元素
学习·算法
阿Y加油吧21 分钟前
回溯算法双杀:子集 + 电话号码的字母组合 | 经典模板题解析
算法·leetcode
wuweijianlove21 分钟前
算法验证与性能测试的统一框架设计的技术3
算法
LabVIEW开发21 分钟前
LabVIEW插值应用
算法·labview·labview知识·labview功能·labview程序