Unblocked Works continued
Time limit:3000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 30515 Accepted Submission (s): 11137
Problem description a province since the implementation of many years of smooth engineering plans, finally built a lot of roads. But it's not good to have more roads,
every time you go from one town to another, there are many ways to choose, and some programmes are far shorter than others. This makes pedestrians very troubled.
Now that you know the starting and ending points, you can figure out how much distance you need to walk from the start to the end.
Input This topic contains multiple sets of data, please process to the end of the file.
The first row of each group of data contains two positive integers N and M (0<n<200,0<m<1000), representing the number of existing towns and the number of roads that have been built. The towns were numbered 0~n-1.
Next is the M-Line road information. Each line has three integers a,b,x (0<=a,b<n,a!=b,0<x<10000), indicating that there is a two-way road with X length between town A and town B.
The next line has two integer s,t (0<=s,t<n), representing the starting and ending points, respectively.
Output for each set of data, in a row, the shortest distance to walk. If there is no route from S to T, then output-1.
Sample Input
3 30 1 10 2 31 2 10 23 10 1 11 2
Sample Output
2-1
Idea: Typical Dijkstra, but there are traps: there may be many roads between the two towns, which are easily overlooked.
#include <iostream> #include <cstdio> #include <cstring> #define INF 0x7fffffffusing namespace Std;int N,m,a,b,c;int s,e;int mapp[205][205];int dist[205];bool book[205];void ini () {memset (book)); for (int i=0;i<n;i++)//initialization uses a little technique with the symmetric nature of the graph. for (int j=i;j<n;j++) {if (i==j) mapp[i][j]=0; else Mapp[i][j]=mapp[j][i] =inf; } while (m--) {cin>>a>>b>>c; if (c<mapp[a][b]) mapp[a][b]=mapp[b][a]=c; If very easy to throw away. } cin>>s>>e; for (int i=0;i<n;i++)//dist[] Initializes the distance between a series of points that are directly connected to the source point S. Dist[i]=mapp[s][i];} void Dijkstra () {for (int j=0;j<n;j++) {int cur=-1; for (int i=0;i<n;i++) {if (!book[i]) {if (cur==-1| | Dist[cur]>dist[i]) cur=i; }} book[cur]=1; for (int i=0;i<n;i++) {if (Mapp[cur][i]!=inf&&dist[i]>dist[cur]+mapp[cur][i]) Dist[i]=dist[cur]+map P[cur][i]; }}}int Main () {while (cin>>n>>m) {ini (); Dijkstra (); if (dist[e]==inf) cout<< "-1" <<endl; else cout<<dist[e]<<endl; } return 0;}
Hduoj 1874 (Shortest way Dijkstra)