UVa 523 - Minimum Transport Cost

題目:在幾個城市間運送貨物,每個城市間的道路有固定的花費,

            經過某個特定城市也有一個固定的花費,求最小代價和路徑。

分析:圖論、最短路。使用floyd算法求解多元最短路記錄路徑即可。

            記錄每個節點的後繼既可以保存路徑;

說明:這道題真的很想吐槽:

            1、輸入的格式沒有城市個數,需要字符串轉成數字統計個數;

            2、輸出格式描述不是很清晰,每條路徑建都要有一個空行;

            3、輸出格式使用字典序優化,然後就WA了╮(╯▽╰)╭。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define oo 10000000

int dist[1001][1001];
int next[1001][1001];
int cost[1001];

int string_to_array(char buf[], int d[])
{
	int count = 0, sign = 1, value = 0;
	int len = strlen(buf);
	buf[len] = ' ';
	buf[len+1] = 0;
	for (int i = 0; buf[i]; ++ i) {
		if (buf[i] == '-') {
			sign = -1; 
		}else if (buf[i] >= '0' && buf[i] <= '9') {
			value = value*10 + buf[i]-'0';
		}else {
			d[++ count] = sign * value;
			if (d[count] == -1) { // -1 -> +oo
				d[count] = oo;
			}
			value = 0;
			sign  = 1;
		}
	}
	return count;
}

int main()
{
	int  m, cases = 0;
	char buf[10000];
	scanf("%d", &m);
	while (m --) {
		int city1, city2, total_cost;
		while (gets(buf) && !buf[0]);
		int n = string_to_array(buf, dist[1]);
		for (int i = 2; i <= n; ++ i) {
			while (gets(buf) && !buf[0]);
			string_to_array(buf, dist[i]);
		}
		while (gets(buf) && !buf[0]);
		string_to_array(buf, cost);
		
		for (int i = 1; i <= n; ++ i) {
			for (int j = 1; j <= n; ++ j) {
				next[i][j] = j;
			}
		}

		// floyd
		for (int k = 1; k <= n; ++ k) {
			for (int i = 1; i <= n; ++ i) {
				for (int j = 1; j <= n; ++ j) {
					if (dist[i][j] > dist[i][k] + dist[k][j] + cost[k]) {
						dist[i][j] = dist[i][k] + dist[k][j] + cost[k];
						next[i][j] = next[i][k];
					}
				}
			}
		}
		
		while (gets(buf) && buf[0]) {
			sscanf(buf, "%d%d", &city1, &city2);
			if (cases ++) {
				puts("");
			}
			printf("From %d to %d :\n", city1, city2);
			printf("Path: %d",city1);
			total_cost = dist[city1][city2];
			while (city1 != city2) {
				printf("-->%d",next[city1][city2]);
				city1 = next[city1][city2];
			}
			printf("\nTotal cost : %d\n",total_cost);
		}
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值