(阶段三 dijkstra1.4)HDU 1596 find the safest road(最短路的变形题:求乘积,求最大值)

#include <iostream>
#include <cstdio>

using namespace std;

const int maxn = 1100;
const int inf = -100;
double map[maxn][maxn];
double d[maxn];
int s[maxn];
int n, m;

int start, end;

double dijkstra(int v) {
	int i;
	for (i = 1; i <= n; ++i) {
		s[i] = 0;
		d[i] = map[v][i];
	}

	s[v] = 1;
	d[v] = 1;
	int j;
	for (i = 1; i < n; ++i) {
		double min = inf;
		int pos;

		for (j = 1; j <= n; ++j) {
			if (!s[j] && min < d[j]) {
				pos = j;
				min = d[j];
			}
		}

		s[pos] = 1;

		/**
		 * 此题是最短路径的变形体。
		 * 原来最短路的特征是: 求最短路,求最小值
		 * 而这道题是求乘积,求最大值
		 */
		for (j = 1; j <= n; ++j) {
			if (!s[j] && (d[j] < (d[pos] * map[pos][j]))) {
				d[j] = d[pos] * map[pos][j];
			}
		}
	}

	return d[end]; //返回所要求的源节点到n节点的最短路径
}


int main() {
	while (scanf("%d", &n) != EOF) {
		int i, j;
		for (i = 1; i <= n; ++i) { //初始化..所有的节点之间都不相通
			for (j = 1; j <= n; ++j) {
				map[i][j] = inf;
			}
		}

		double temp;
		for(i = 1 ; i <= n ; ++i){
			for(j = 1 ; j <= n ; ++j){
				scanf("%lf",&temp);
				map[i][j] = temp;
			}
		}

		int q;
		scanf("%d",&q);
		while(q--){
			scanf("%d%d",&start,&end);

			if(start == end){
				printf("%.3lf\n",map[start][end]);
			}else {
				if(dijkstra(start) > 0){
					printf("%.3lf\n",dijkstra(start));
				}else{
					printf("What a pity!\n");
				}
			}
		}
	}

	return 0;

}

你可能感兴趣的:((阶段三 dijkstra1.4)HDU 1596 find the safest road(最短路的变形题:求乘积,求最大值))