hiho_1089_floyd最短路

题目

    floyd算法求所有顶点之间的最短路,典型的模板题。唯一需要注意的是两个顶点之间可能有多条边直接相连,在初始化的时候,直接选择最小的长度作为两点间的距离即可。

实现

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<unordered_map>
#include<list>
#include<string>
#include<string.h>
#include<set>
using namespace std;
int min_dist[105][105];

int main(){
	int n, m, u, v, d;
	scanf("%d %d", &n, &m);
	memset(min_dist, 0x0F, sizeof(min_dist));
	for (int i = 1; i <= n; i++)
		min_dist[i][i] = 0;
	for (int i = 0; i < m; i++){
		scanf("%d %d %d", &u, &v, &d);
		if (min_dist[u][v] > d)  //可能存在两个点之间有多条直接相连的边,取最小的那一条即可
			min_dist[u][v] = min_dist[v][u] = d;
	}
	//floyd算法求最短路
	for (int k = 1; k <= n; k++){
		for (int i = 1; i <= n; i++){
			for (int j = 1; j <= n; j++){
				if (min_dist[i][j] > min_dist[i][k] + min_dist[k][j])
					min_dist[i][j] = min_dist[i][k] + min_dist[k][j];
			}
		}
	}
	for (int i = 1; i <= n; i++){
		for (int j = 1; j <= n; j++)
			printf("%d ", min_dist[i][j]);
		printf("\n");
	}
	return 0;
}

 

posted @ 2016-06-04 14:50  农民伯伯-Coding  阅读(191)  评论(0编辑  收藏  举报