FJ took a friend to visit his farm, set out from his house to barn (barn, barn or garage), and then returned to his house from barn, it is required that you do not go back in the same way.
Build a graph: Take the super Source Vertex and connect it with an edge of the House. The capacity is 2. Take the capacity of the edge between the barn and the super sink vertex as 2. The middle graph creation method is like code.
Code:
[Cpp]
# Include <iostream>
# Include <queue>
# Define maxe 400005
# Define maxn1005
# Define INF 0x7fffffff
Using namespace std;
Struct Edge
{
Int v, next;
Int p, f;
Edge (int vv, int pp, int ff, int x): v (vv), p (pp), f (ff), next (x ){}
Edge (){}
} E [maxe];
Int dist [maxn], vis [maxn], cur [maxn];
Int size, pre [maxn], head [maxn], mimf;
/*
Maximum Minimum fee flow:
Use the shortest path algorithm to find an extended path with the minimum cost.
Because the traffic can be rolled back, there is a negative side, using SPFA or Bellman_Ford.
Modify the traffic on the nearest short circuit (consistent with the maximum flow algorithm)
The fee for each path is mimf * dist [T] (the maximum flow that can be passed on this path * the fee for each unit of traffic)
The sum of the fees for all paths is the total minimum fee.
*/
Void AddEdge (int u, int v, int p, int f)
{
E [size] = Edge (v, p, f, head [u]);
Head [u] = size ++;
E [size] = Edge (u,-p, 0, head [v]);
Head [v] = size ++;
}
Bool SPFA (int s, int t, int n)
{
Int f, u, v, I;
Queue <int> que;
While (! Que. empty () que. pop ();
Memset (vis, 0, sizeof (vis ));
Memset (dist, 0x7f, sizeof (dist ));
Memset (pre,-1, sizeof (pre ));
Que. push (s), vis [s] = true, dist [s] = 0;
While (! Que. empty ()){
U = que. front ();
Que. pop (), vis [u] = false;
For (I = head [u]; I! =-1; I = e [I]. next ){
V = e [I]. v;
If (e [I]. f & dist [v]> dist [u] + e [I]. p ){
Dist [v] = dist [u] + e [I]. p;
Pre [v] = u;
Cur [v] = I;
/* Pre, cur array record path */
If (! Vis [v]) {
Que. push (v );
Vis [v] = 1;
}
}
}
}
If (pre [t] =-1) return false;
Return true;
}
Void Update (int u) // modify the traffic on the path to the minimum fee augmented path
{
If (pre [u] =-1) return;
If (mimf> e [cur [u]. f) mimf = e [cur [u]. f;
Update (pre [u]);
E [cur [u]. f-= mimf;
E [cur [u] ^ 1]. f + = mimf;
}
Int main ()
{
Int n, m, a, B, c, ans;
Scanf ("% d", & n, & m );
Memset (head,-1, sizeof (head ));
Size = 0;
While (m --){
Scanf ("% d", & a, & B, & c );
AddEdge (a, B, c, 1); // because it is an undirected graph, two edges are added.
AddEdge (B, a, c, 1 );
}
AddEdge (0, 1, 0, 2 );
AddEdge (n, n + 1, 0, 2 );
Ans = 0;
While (SPFA (0, n + 1, n )){
Mimf = INF;
Update (n + 1 );
Ans + = mimf * dist [n + 1];
}
Printf ("% d \ n", ans );
Return 0;
}