最短路之朴素版的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;
}
相关推荐
mit6.82439 分钟前
二分+贪心
算法
programhelp_1 小时前
特斯拉 MLE 超详细面经 + 避坑
数据结构·人工智能·算法·面试·职场和发展
越甲八千2 小时前
深入了解迭代器erase()之后的失效逻辑
算法
躺柒2 小时前
读人工智能全球格局:未来趋势与中国位势06人类的未来(下)
大数据·人工智能·算法·ai·智能
L_Aria2 小时前
6421. 【NOIP2019模拟11.11】匹配
c++·算法·动态规划
骇城迷影3 小时前
代码随想录:哈希表篇
算法·哈希算法·散列表
智者知已应修善业3 小时前
【PAT乙级真题解惑1012数字分类】2025-3-29
c语言·c++·经验分享·笔记·算法
每天要多喝水3 小时前
动态规划Day30:买卖股票
算法·动态规划
v_for_van3 小时前
力扣刷题记录6(无算法背景,纯C语言)
c语言·算法·leetcode
-To be number.wan4 小时前
算法学习日记 | 双指针
c++·学习·算法