POJ 1734 Sightseeing Trip (最小环)

#include <stdio.h>
#define MAX_POINTS 101
#define INF 300000

int numOfPoints, numOfRoads;
int initialDist[MAX_POINTS][MAX_POINTS];
int shortestDist[MAX_POINTS][MAX_POINTS];
int pre[MAX_POINTS][MAX_POINTS];
int path[MAX_POINTS];
int num;

int getMin(int x, int y){
	return x < y ? x : y;
}

int main(){
	//freopen("input.txt", "r", stdin);

	while (scanf("%d", &numOfPoints) != EOF){
		if (numOfPoints == -1)
			break;
		int from, to;
		for (from = 1; from <= numOfPoints; from++)
			for (to = 1; to <= numOfPoints; to++){
				initialDist[from][to] = shortestDist[from][to] = INF;
				pre[from][to] = from;
			}

		scanf("%d", &numOfRoads);
		int dist;
		int i;
		for (i = 1; i <= numOfRoads; i++){
			scanf("%d%d%d", &from, &to, &dist);
			initialDist[from][to] = shortestDist[from][to] = initialDist[to][from] = shortestDist[to][from] = getMin(dist, initialDist[from][to]);
		}

		int minLen = INF;
		int pass;
		for (pass = 1; pass <= numOfPoints; pass++){
			//遍历所有环,from-> (因为最小环要求不经过相同的景点,所以走不包含pass的最短路,因为还没计算呢) -> to -> pass -> from
			for (from = 1; from < pass; from++)
				for (to = from + 1; to < pass; to++){
					int routeLen = shortestDist[from][to] + initialDist[from][pass] + initialDist[pass][to];
					if (routeLen < minLen){
						minLen = routeLen;
						int prePoint = to;
						num = 0;
						while (prePoint != from){
							path[num++] = prePoint;
							prePoint = pre[from][prePoint];
						}
						path[num++] = from;
						path[num++] = pass;
					}
				}

			for (from = 1; from <= numOfPoints; from++)
				//需记录路径,不能对称优化
				for (to = 1; to <= numOfPoints; to++)
					if (shortestDist[from][pass] + shortestDist[pass][to] < shortestDist[from][to]){
						shortestDist[from][to] = shortestDist[from][pass] + shortestDist[pass][to];
						pre[from][to] = pre[pass][to];
					}
		}

		if (minLen == INF)
			printf("No solution.\n");
		else {
			for (i = 0; i < num; i++)
				printf("%d ", path[i]);
			printf("\n");
		}

	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值