poj3268(置换矩阵思想)

题意:一群牛分别从1~n号农场赶往x号农场参加聚会,农场与农场之间的路时单向的,在n个农场之间有m条路,给出 a ,b , t表示从a号农场到b号农场需要t时间。 每头牛都会选择最短的路,问来回路上(i→x+x→i)花费时间最长的牛花费的时间是多少?

 

题解:一眼看过去很简单,先计算x农场到其他农场用的最短时间,在枚举其他农场到x农场的最短时间,记录下最大来回时间即可。的确,不过我们算一算时间复杂度,在枚举其他农场到x农场的最短时间时,最大复杂度为O(n^3)。也就是1000^3,很明显超过了2000ms。所以我们要想办法把枚举过程的复杂度降下来。  这里可以采用置换矩阵,因为是路径时单向的,我们交换 map[i][j] 与 map[j][i] 的值,那么枚举过程就变成了求x到其他农场的最短时间,这里就变成了O(n^2)的算法。

 

Description

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: NM, and X 
Lines 2..M+1: Line i+1 describes road i with three space-separated integers: AiBi, 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.
posted @ 2018-02-28 11:01  cglong  阅读(211)  评论(0编辑  收藏  举报