最短路之朴素版的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;
}
相关推荐
紫陌涵光24 分钟前
77. 组合
c++·算法·leetcode·深度优先
小汉堡编程27 分钟前
LeekCode第3767题选择K个任务的最大总分:详细思考过程幽默解析 专门为小白准备
算法·leetcode·贪心算法·编程·小白专用教程
小白菜又菜36 分钟前
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
python·算法·leetcode
We་ct44 分钟前
LeetCode 222. 完全二叉树的节点个数:两种解法详解(BFS + 二分查找优化)
数据结构·算法·leetcode·typescript
小白菜又菜1 小时前
Leetcode 234. Palindrome Linked List
python·算法·leetcode
阿里云大数据AI技术1 小时前
阿里云PAI助力新一代Qwen3.5模型发布!
人工智能·算法
小白菜又菜2 小时前
Leetcode 221. Maximal Square
算法·leetcode·职场和发展
流云鹤2 小时前
牛客周赛Round 132(无F)
算法
Lee川2 小时前
深入解析:从内存模型到作用域陷阱——JavaScript变量的前世今生
javascript·算法
㓗冽2 小时前
回文数2(字符串)-基础题97th + 加法器(字符串)-基础题98th + 构造序列(字符串)-基础题99th
算法