Given a point n and m edges directed graph, there may be multiple edges in FIG loopback and all are positive edge weights.
Please find the shortest distance from point 1 to point number n, n number if you can not go from point 1 point, then output -1.
Input Format
The first line contains the integers n and m.
Next m lines contains three integers x, y, Z, represents between points x and y point to have an edge side length z.
Output Format
Output an integer, represents the shortest distance to the point 1 point number n.
If the path does not exist, the output of -1.
data range
. 1 ≤ n- ≤ 500 1≤n≤500,
. 1 ≤ m ≤ 10 . 5 1≤m≤105,
FIG relates to a side not more than 10,000.
Sample input:
3 3
1 2 2
2 3 1
1 3 4
Sample output:
3
#include<iostream> #include<cstring> #include<algorithm> using namespace std; const int N=510; int dis[N],g[N][N],m,n; bool st[N]; int dijkstra(){ memset(dis,0x3f,sizeof(dis)); dis[1]=0; 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[j],dis[t]+g[t][j]); } } if(dis[n]==0x3f3f3f3f)return -1; return dis[n]; } int main(void){ 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); } cout<<dijkstra()<<endl; return 0; }