Dijkstra算法1.0

来源:互联网 发布:线性变换旋转矩阵 编辑:程序博客网 时间:2024/06/03 16:58

Silver Cow Party poj3268
One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.

Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow’s return route might be different from her original route to the party since roads are one-way.

Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?
Input
Line 1: Three space-separated integers, respectively: N, M, and X
Lines 2.. M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.
Output
Line 1: One integer: the maximum of time any one cow must walk.
Sample Input
4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3
Sample Output
10
Hint
Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.
题目大意是有n头奶牛,要去编号为X的农场参加聚会,给你M条单项路径,求每头奶牛来回最短路程条件下路程最长的那个。
很经典的最短路问题,我第一次拿到这题时是刚开始学习最短路算法和图的遍历,于是一顿操作猛如虎,先用DFS写了一发,猛然发现是算来回最短路的(坑一),我只搜了去的路,后来又想到可以把图翻转过来,再搜索一遍就可以,但是不出所料时间超限了,于是我开始看书。先看了弗洛伊德算法(Floyd),发现这题就很明显了,但是O(n³)的时间复杂度过不去,于是又想我只要算每个点到X的最短路径和X到每个点的最短路径就行了(坑二),代码如下:
这里写图片描述
代码链接 点击这里
这里有个致命错误(当然样例过了23333),比如样例:
4 8 2
1 2 10
2 1 1
1 3 4
3 1 6
4 1 2
3 4 4
2 3 3
3 2 1
正确输出:14
本地输出:19
调试过程中
我发现4号奶牛路径为4→1 1→2 时间12;2→3 3→4 时间7;
但正确路径应该是4→1 1→3 3→2 时间7;2→3 3→4 时间7;
为什么会出现这样的结果?原因在于我的算法固定了中转的终点和起点,也就是每次通过一个源点中转时终点固定,而如果通过这个点无法中转到终点,就排除掉了可以通过这个点转到其他点然后再到终点的可能,这也是为什么没有4→1 1→3 3→2出现的可能,因为数组中没有保存4→3这条路(4→1 1→3),起点固定也是同理。
想清楚这个问题后我又看了迪杰斯特拉算法(Dijkstra),超牛逼的单源最短路算法,(大神喝个咖啡就想出来的算法我整了一个多小时才看明白(邻链表存储暂时还没搞懂))代码如下:
这里写图片描述
这里写图片描述
代码链接点击这里
通过这道题的学习,感觉弗洛伊德算法核心是多源最短路,绝对不能瞎JB改。
迪杰斯特拉计算单源最短路时间复杂为O(n²)时间复杂度可以用邻接表优化为O((M+N)logN)。

原创粉丝点击