Problem Description 某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。
现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
Input 本题目包含多组数据,请处理到文件结束。 每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0~N-1编号。 接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。 再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。
Output 对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
Sample Input 3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
Sample Output 2 -1
分析 这道题是单源点最短路径问题,可以采用SPFA。 题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1874 SPFA算法 https://blog.csdn.net/qq_40061421/article/details/82054784
#include<iostream> #include<queue> #include<cstring> using namespace std; #define N 200 + 10 #define INF 0x3f3f3f3f int a[N][N],visited[N],dist[N]; int n,m; void SPFA(int s) { memset(dist,INF,sizeof(dist)); memset(visited,0,sizeof(visited)); dist[s] = 0; queue<int> q; q.push(s); visited[s] = 1; while(!q.empty()) { int v = q.front(); q.pop(); visited[v] = 0; for(int i = 0; i < n; i++) if(dist[v] + a[v][i] < dist[i]) { dist[i] = dist[v] + a[v][i]; if(!visited[i]) {//如果没有在队列中 q.push(i); visited[i] = 1; } } } } int main() { while(cin >> n >> m) { memset(a,INF,sizeof(a)); for(int i = 0,j,k,w; i < m; i++) { cin >> j >> k >> w; if(w < a[j][k]) a[j][k] = a[k][j] = w;//这里需要进行判断,否则会出错 } int s,t; cin >> s >> t; SPFA(s); if(dist[t] == INF) cout << -1 << endl; else cout << dist[t] << endl; } return 0; }