Smooth engineering continued time limit: 3000/1000 MS (Java/others) memory limit: 32768/32768 K (Java/Others)
Total submission (s): 26970 accepted submission (s): 9719
Problem description a province has finally built many roads since its smooth engineering plan was implemented for many years. However, when there are too many roads, there are many ways to choose from every town to another town, some solutions are much shorter than others. This makes pedestrians very difficult.
Now you know the start and end points. Calculate the shortest distance from the start point to the end point.
The input question contains multiple groups of data. Please process the data until the end of the file.
The first row of each data group contains two positive integers n and M (0 <n <1000, 0 <m <), representing the number of existing towns and the number of constructed roads respectively. The towns are 0 ~ N-1 number.
Next is m-line road information. Each row has three integers, A, B, x (0 <= A, B <n,! = B, 0 <x <10000) indicates that there is a two-way road with x length between town a and town B.
The next line has two integers, T (0 <= S, T <n), representing the start point and the end point respectively.
For each group of data, output the shortest distance to walk in one row. If there is no route from S to T, output-1.
Sample Input
3 30 1 10 2 31 2 10 23 10 1 11 2
Sample output
2-1
The template question for Dijkstra to find the shortest path.
#include <stdio.h>#include <string.h>#define maxn 202const int maxint = 100000000;int n, m; int dist[maxn], map[maxn][maxn];bool vis[maxn];int getNextNode(){ int i, tmp = maxint, u = -1; for(i = 0; i < n; ++i){ if(dist[i] != -1 && !vis[i] && dist[i] < tmp){ tmp = dist[i]; u = i; } } return u;}void Dijkstra(int start, int end){ memset(dist, -1, sizeof(dist)); memset(vis, 0, sizeof(vis)); int i, tmp, u; dist[start] = 0; vis[start] = true; for(i = 0; i < n; ++i){ if(map[start][i] != -1) dist[i] = map[start][i]; } u = getNextNode(); while(u != -1){ for(i = 0; i < n; ++i){ if(map[u][i] != -1 && !vis[i]){ tmp = dist[u] + map[u][i]; if(dist[i] == -1 || dist[i] > tmp) dist[i] = tmp; } } vis[u] = true; u = getNextNode(); }}int main(){ int i, a, b, x, s, t; while(scanf("%d%d", &n, &m) != EOF){ memset(map, -1, sizeof(map)); for(i = 0; i < m; ++i){ scanf("%d%d%d", &a, &b, &x); if(map[a][b] != -1 && x > map[a][b]) continue; map[a][b] = map[b][a] = x; } scanf("%d%d", &s, &t); Dijkstra(s, t); printf("%d\n", dist[t]); } return 0;}