Lucy lives in city GZ. There are N (2 <= N && N <= 100) towns in GZ。There are M (1 <= M <= 1000) two-way roads connecting the towns, and every road has a length w (1 <= w <= 1000). Lucy’s home is in town 1, and the school is in town N. Every day, Lucy goes to school on time, she always takes the shortest path. Please write a program to calculate the length of the shortest path from town 1 to town N.
The input contains several test cases.
The first line contains two integers N, M. The following M lines each contains three integers x, y, w, meaning there is a two-way road between town x and y, and the length of the road is w.
The input will be terminated by EOF.
Output the length of the shortest path from town 1 to town N. It is guaranteed that there is at least one path from town 1 to town N.
2 12 1 4793 31 3 101 2 42 3 4
4798
这题比较传统,找最短路径,所以知道求最短路径算法的话,这题还是不难的。我用的是dijkstra算法。
#include <iostream>
#include <cstring>
using namespace std;
int edge[110][110];
int const my_MAX = 9999;
int dijkstra(int s, int d)
{
int dis[110];
bool vis[110];
int v, i;
memset(dis, my_MAX, sizeof(dis));
dis[0] = 0;
dis[s] = 0;
memset(vis, false, sizeof(vis));
while (true) {
int min = my_MAX;
for (i = 1; i <= d; i++) {
if (!vis[i] && dis[i] < min) {
v = i;
min = dis[i];
}
}
if (min == my_MAX)
break;
vis[v] = true;
dis[v] = min;
for (i = 1; i <= d; i++) {
if (!vis[i] && dis[i] > edge[v][i] + dis[v])
dis[i] = edge[v][i] + dis[v];
}
}
return dis[d];
}
int main()
{
// freopen("input.txt","r",stdin);
int n, m;
while (cin >> n >> m) {
int x, y, d;
memset(edge, my_MAX, sizeof(edge));
for (int i = 0; i < m; i++) {
cin >> x >> y >> d;
edge[x][y] = d;
edge[y][x] = d;
}
cout << dijkstra(1,n) << endl;
}
return 0;
}