POJ 2135 Farm Tour

POJ 2135 Farm Tour

Description

When FJ's friends visit him on the farm, he likes to show them around. His farm comprises N (1 <= N <= 1000) fields numbered 1..N, the first of which contains his house and the Nth of which contains the big barn. A total M (1 <= M <= 10000) paths that connect the fields in various ways. Each path connects two different fields and has a nonzero length smaller than 35,000.

To show off his farm in the best way, he walks a tour that starts at his house, potentially travels through some fields, and ends at the barn. Later, he returns (potentially through some fields) back to his house again.

He wants his tour to be as short as possible, however he doesn't want to walk on any given path more than once. Calculate the shortest tour possible. FJ is sure that some tour exists for any given farm.
Input
* Line 1: Two space-separated integers: N and M.

* Lines 2..M+1: Three space-separated integers that define a path: The starting field, the end field, and the path's length.
Output
A single line containing the length of the shortest tour.
Sample Input
4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2
Sample Output

6

分析:看起来很像最短路径类的题目,然而并不是。。原因是无法处理来回两条最短路径之间的关系(比如贪心很明显能举出反例)。

但是使用网络流可以轻松解决,这里对于算法不赘述:一个最小费用最大流就可以。我想说的是关于建图的问题。之前我的一个误区是:两点之间连无向边时,应该存成一个边。但实际上,无向边就是等价于两条有向边,这两条边的费用都是这条无向边的费用。这样才正确,而不是建一条边。因为这样会导致一条边不堪重负(它一方面要负担一个方向上权值为v的流量,另一方面要负担反方向上同样权值为v的流量)。

与此同时,两个流量分别要有权值为-v的用于增广的反向流量,这就要连四条边,也就是连两次流量边。(这点很重要,必须理解透彻。)


代码
posted @ 2017-12-07 21:11  xuzihanllaa  阅读(126)  评论(0编辑  收藏  举报