3B - Shortest

Topic link
in the annual school competition, all students finalists will receive a very nice t-shirt. But whenever our staff to hundreds of pieces of clothing shipped back to the stadium from the store when they are very tired! So now they want to find the shortest route to the stadium from the store, you can help them?

Input
input includes a plurality of sets of data. The first line of each two integers N, M (N <= 100 , M <= 10000), N represents a few street intersections Chengdu, reference numeral 1 is to store the location of the intersection, the intersection designated N is the location of the stadium, M indicates a couple of choices in Chengdu. N = M = 0 indicates the end of input. Next M rows, each row comprising three integers A, B, C (1 < = A, B <= N, 1 <= C <= 1000), indicates there is a path between the intersection A and the intersection B, we staff need to C-minute time traveled this road.

Input line to ensure the presence of at least one track to store.

Output
For each input and output line, represents the track workers come from the store minimum time

Sample Input
2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0
Sample Output
3
2

solution

floyd template title
Shortest seek a point (tentatively A) to another point (B), the passing point A to point must be the shortest path
is well documented, if not passing point A to point not the shortest road, it must also be a shorter road to reach point B, contradictory
so just take away all the points of all the relaxation, you can find the shortest path from a to any point

Code

#include <iostream>
using namespace std;

const int INF = 233366666;
int edge[105][105];

void floyd(int n){
	for(int k=1; k<=n; ++k){//枚举所有的点作为中转点
		for(int i=1; i<=n; ++i){
			for(int j=1; j<=n; ++j)
				if( edge[i][k] + edge[k][j] < edge[i][j]){//若i到j的距离大于i到k+k到j的距离, 松弛之
					edge[j][k] = edge[j][i] + edge[i][k];
				}
			}
		}
	}
}

int main(){
	int n, m;
	while(cin >> n >> m){
		if(n==0 && m==0) break;
		for(int i=1; i<=n; ++i){
			for(int j=1; j<=n; ++j){
				edge[i][j] = INF;
			}
		} 
		int a, b, c;
		for(int i=1; i<=m; ++i){
			cin >> a >> b >> c;
			edge[a][b] = c;
			edge[b][a] = c;
		}
		floyd(n);
		cout << edge[1][n] << endl;
	}
	
	return 0;
}
发布了14 篇原创文章 · 获赞 0 · 访问量 126

Guess you like

Origin blog.csdn.net/loaf_/article/details/104011051