给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为正值。
请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
如果路径不存在,则输出-1。
数据范围
1≤n≤500,
1≤m≤105,
图中涉及边长均不超过10000。
输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
具体代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510;
int n, m;
int g[N][N]; //稠密图用邻接矩阵存数据
int dist[N]; //dist存储从1到n点的距离
bool st[N]; //判断是否存储过
int dijkstra()
{
//将dist所有点的距离都设为无穷代表无距离
memset(dist, 0x3f, sizeof dist);
//第一个点,距离自己的位置是0
dist[1] = 0;
//有多少点迭代多少次
for(int i = 0; i < n; i ++)
{
int t = -1;
//寻找最近的点
for(int j = 1; j <= n; j ++)
if(!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
//标记
st[t] = true;
//更新
for(int j = 1; j <= n; j ++)
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
if(dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while(m --)
{
int x, y, z;
cin >> x >> y >> z;
//邻接矩阵存储
g[x][y] = min(g[x][y], z);
}
//输出
cout << dijkstra() << endl;
return 0;
}