六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 37|回复: 0

【floyd记录路径】HDU 1385 Minimum Transport Cost

[复制链接]

升级  68.4%

272

主题

272

主题

272

主题

进士

Rank: 4

积分
842
 楼主| 发表于 2013-1-26 12:35:15 | 显示全部楼层 |阅读模式
http://acm.hdu.edu.cn/showproblem.php?pid=1385

题意: 找一个路径使得从一个地方坐的士到另一个地方花费最小,其中除了起点和终点,途中经过的站点要收费

Sample Input
5
0 3 22 -1 4
3 0 5 -1 -1
22 5 0 9 20
-1 -1 9 0 4
4 -1 20 4 0
5 17 8 3 1
1 3
3 5
2 4
-1 -1
0

Sample Output
From 1 to 3 :
Path: 1-->5-->4-->3
Total cost : 21

From 3 to 5 :
Path: 3-->4-->5
Total cost : 16

From 2 to 4 :
Path: 2-->1-->5-->4
Total cost : 17

#include <iostream>#include <fstream>#include <algorithm>#include <string>#include <set>//#include <map>#include <queue>#include <utility>#include <stack>#include <list>#include <vector>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>//#include <ctime>#include <ctype.h>using namespace std;#define inf 999999999    //用0x3fffffff太大溢出,纠结了良久#define M 205int dist[M][M], n, b[M], path[M][M];void floyd (){    int i, j, k;    for (i = 1; i <= n; i++)        for (j = 1; j <= n; j++)            path[j] = j;    //记录路径数组初始化,表示从i到j经过的第一个站    for (k = 1; k <= n; k++)    {        for (i = 1; i <= n; i++)        {            for (j = 1; j <= n; j++)            {                int tp = dist[k] + dist[k][j] + b[k];               //溢出之地,因为+了b[k],其实先判断是否有路会更保险                if (tp < dist[j])                    dist[j] = tp, path[j] = path[k];                else if (tp == dist[j] && path[k] < path[j])                    path[j] = path[k];    //按字典序记录路径            }        }    }}int main(){    int i, j, u, v, tp;    while (scanf ("%d", &n), n)    {        for (i = 1; i <= n; i++)        {            for (j = 1; j <= n; j++)            {                scanf ("%d", dist+j);                if (dist[j] == -1)                    dist[j] = inf;            }        }        for (i = 1; i <= n; i++)            scanf ("%d", b+i);        floyd();        while (scanf ("%d%d", &u, &v), (u != -1 || v != -1))        {            printf ("From %d to %d :\n", u, v);            printf ("Path: %d", u);            tp = u;            while (u != v)            {                printf ("-->%d", path[v]);                u = path[v];            }            printf ("\nTotal cost : %d\n\n", dist[tp][v]);        }    }    return 0;}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表