Given a directed graph with n points and m edges, there may be multiple edges and self-loops in the graph, and all edge weights are positive.
Please find the shortest distance from point 1 to point n. If it is impossible to go from point 1 to point n, output −1.
Input format
The first line contains integers n and m.
Each of the next m lines contains three integers x, y, z, indicating that there is a directed edge from point x to point y, and the edge length is z.
Output Format
Output an integer representing the shortest distance from point 1 to point n.
If the path does not exist, output −1.
The data range is
1≤n≤500,
1≤m≤105,
and the length of the sides involved in the figure does not exceed 10000.
Input sample:
3 3
1 2 2
2 3 1
1 3 4
Output sample:
3
#include<bits/stdc++.h>
using namespace std;
const int N = 510;
int g[N][N];
int dist[N];
bool vis[N];
int n, m;
int dijkstra()
{
//初始化
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
//循环n-1次
for(int i=0; i<n-1; i++) {
int t = -1;
//找出dist中的最小值
for(int j=1; j<=n; j++) {
if(!vis[j] && (t == -1 || dist[t] > dist[j])) t = j;
}
//用该点更新距离
for(int j=1; j<=n; j++) {
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
//标记
vis[t] = true;
}
if(dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main()
{
//初始化
memset(g, 0x3f, sizeof g);
cin >> n >> m;
int a, b, c;
for(int i=0; i<m; i++) {
cin >> a>> b >> c;
g[a][b] = min(g[a][b], c);
}
cout << dijkstra() << endl;
return 0;
}