您的位置:首页 > 其它

hdu1385 Minimum Transport Cost(经典字典序输出路径)

2016-10-22 20:03 344 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1385

题意:给你一个矩阵,每个矩阵元素表示i到j的花费,每过一个点还需要过路费,求起点到终点的最小花费。若满足最小花费的路径不止一条,则输出字典序最小的。

ps:刚开始拿dijkstra写崩了,本来用栈就已经很麻烦了,居然又有个字典序,这怎么搞啊,转变成字符串越写越麻烦。。于是强大的floyd。话说居然没有对n的限制,上一道超时的阴影还在。。

思路:感觉这题就是为floyd设计好的,一目了然啊。一方面多了一个过路费,spfa和dijkstra都需要另外对其考虑,而floyd正好有个对第三节点的遍历。这样第三节点除了记录路径,还有保存过路费,这也太合适了吧。另一方面对字典序的处理,那两种都需要拉出来将其转化为字符串,而在这里直接对后继元素比较即可,要知道能保存后继元素的只有floyd啊。。orz。。。

#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>

using namespace std;

typedef long long LL;

const int N = 1005;
const int INF = 0x3f3f3f3f;

int G

, pre

, n, cost
;

void floyd()
{
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
if(G[i][k]+G[k][j]+cost[k] < G[i][j])
{
G[i][j] = G[i][k]+G[k][j]+cost[k];
pre[i][j] = pre[i][k];
}
else if(G[i][k]+G[k][j]+cost[k] == G[i][j])
{
pre[i][j] = min(pre[i][j], pre[i][k]);
}
}
}

int main()
{
// freopen("in.txt", "r", stdin);
int num, s, e;
while(~scanf("%d", &n))
{
if(n == 0) break;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
scanf("%d", &num);
if(num == -1) G[i][j] = INF;
else G[i][j] = num;
pre[i][j] = j;
}
for(int i = 1; i <= n; i++)
scanf("%d", &cost[i]);
floyd();
while(~scanf("%d%d", &s, &e))
{
if(s == -1 && e == -1) break;
int now = pre[s][e];
printf("From %d to %d :\nPath: %d", s, e, s);
if(s == e)
{
printf("\n");
printf("Total cost : 0\n\n");
}
else
{
while(1)
{
printf("-->%d", now);
if(now == e) break;
now = pre[now][e];
}
printf("\n");
printf("Total cost : %d\n\n", G[s][e]);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu