当前位置:   article > 正文

最短路之朴素版的dij板子

最短路之朴素版的dij板子

模板:

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

#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;//注意到这里并没有对st【】进行处理
	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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/830914
推荐阅读
相关标签
  

闽ICP备14008679号