【朴素Dijkstra】AcWing849.Dijkstra求最短路 I
作者:互联网
AcWing849.Dijkstra求最短路 I
题解
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 510, M = 1e5 + 10;
int d[N], n, m;
bool flag[N];
int g[N][N]; //朴素只能用邻接矩阵不然会变成O(nm)
void Dijkstra()
{
memset(d, 0x3f, sizeof d);
d[1] = 0;
for(int i = 0; i < n; ++i)
{
int mi = 0x3f3f3f, k;
for(int j = 1; j <= n; ++j)
if(!flag[j] && d[j] < mi)
mi = d[j], k = j;
flag[k] = true;
for(int j = 1; j <= n; ++j)
if(!flag[j] && mi + g[k][j] < d[j])
d[j] = mi + g[k][j];
}
}
int main()
{
memset(g, 0x3f, sizeof g);
int x, y, z;
scanf("%d%d",&n,&m);
for(int i = 0 ;i < m; ++i)
{
scanf("%d%d%d",&x,&y,&z);
g[x][y] = min(g[x][y], z);
}
Dijkstra();
if(flag[n])
cout << d[n] << endl;
else
cout << -1 << endl;
return 0;
}
标签:int,短路,Dijkstra,AcWing849,include,朴素 来源: https://www.cnblogs.com/czy-algorithm/p/16307350.html