Dijkstra求最短路 I
#include<bits/stdc++.h>
using namespace std;
const int N = 510, M = 1e5 + 10;
int n, m;
int dist[N];//存储每个点到1号点的最短距离
bool st[N];//表示每个点的最短路是否确定
int g[N][N];//稀疏图,用邻接矩阵存储
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for(int i = 1; i <= n; i ++)
{
int t = -1;
//依次找到距离1号点最近的点
for(int j = 1; j <= n; j ++)
{
if(!st[j] &&(t == -1 || dist[j] < dist[t]))
{
t = j;
}
}
st[t] = true;
//用刚找到的点更新其它点到1号点的距离
for(int j = 1; j <= n; j ++)
{
dist[j] = min(dist[j],dist[t] + g[t][j]);
}
}
if(dist[n] == 0x3f3f3f3f)return -1;
else return dist[n];
}
int main()
{
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while (m -- ){
int a, b, c;
cin >> a >> b >> c;
g[a][b] = min(g[a][b], c);
}
int t = dijkstra();
cout << t << endl;
}
数据结构 文章被收录于专栏
数据结构