UVa 523

来源:互联网 发布:辣鸭头淘宝配方 编辑:程序博客网 时间:2024/05/19 03:45

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

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

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

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

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

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

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

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

#include <stdio.h>#include <stdlib.h>#include <string.h>#define oo 10000000int 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 -> +ood[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;}}// floydfor (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
原创粉丝点击