Stoer-Wagner Algorithm
Attached Template
Stoer-Wagner algorithm:
The prim algorithm can not only calculate the minimum spanning tree, but also the "Maximum spanning tree ". The stoer-Wagner algorithm of the minimal cut set is a typical application instance.
Stoer-Wagner algorithm is widely used to solve the minimum cut set.
1. min = maxint, fixed a vertex P
2. Use the s Algorithm Similar to prim to expand the "Maximum Spanning Tree" from vertex P, and record the last extended vertex and last extended edge.
3. Calculate the cut value of the last extended vertex (that is, all edge weights connected to the vertex). If the cut value is smaller than min
4. merge the two endpoints of the last extended edge into a vertex (of course, their edge also needs to be merged. Is this easy to understand ?)
5. Go to 2, merge N-1 times and end
6. Min is the request and the output is Min.
The complexity of prim itself is O (n ^ 2), which is merged n-1 times. The algorithm complexity is O (n ^ 3)
If heap optimization is added to the prim, the complexity will be reduced to O (n ^ 2) logn)
# Include <iostream> <br/> using namespace STD; <br/> # define maxn 511 <br/> int map [maxn] [maxn]; <br/> // model start <br/> inline int min (int A, int B) {<br/> return A> B? B: A; <br/>}< br/> int mincut (INT N) {<br/> int ans = 0x7fffffff; <br/> int node [maxn], dist [maxn]; <br/> bool visit [maxn]; <br/> int I, Prev, J, K; <br/> for (I = 0; I <n; I ++) <br/> node [I] = I; <br/> while (n> 1) {<br/> int maxj = 1; <br/> for (I = 1; I <n; I ++) {<br/> Dist [node [I] = map [node [0] [node [I]; <br/> If (Dist [node [I]> Dist [node [maxj]) <br/> maxj = I; <br/>}< br/> Prev = 0; <br /> Memset (visit, false, sizeof (visit); <br/> visit [node [0] = true; <br/> for (I = 1; I <n; I ++) {<br/> if (I = n-1) {<br/> ans = min (ANS, dist [node [maxj]); <br/> for (k = 0; k <n; k ++) <br/> map [node [k] [node [Prev] = (Map [node [Prev] [node [k] + = map [node [k]] [node [maxj]); <br/> node [maxj] = node [-- N]; <br/>}< br/> visit [node [maxj] = true; <br/> Prev = maxj; <br/> maxj =-1; <br/> for (J = 1; j <n; j ++) {<br/> If (! Visit [node [J]) {<br/> Dist [node [J] + = map [node [Prev] [node [J]; <br/> If (maxj =-1 | Dist [node [maxj] <Dist [node [J]) <br/> maxj = J; <br/>}< br/> return ans; <br/>}< br/> // model end <br/> int main () {<br/> // freopen ("in.txt", "r ", stdin); <br/> int n, m; <br/> int A, B, W; <br/> while (scanf ("% d ", & N, & M )! = EOF) {<br/> // init <br/> memset (MAP, 0, sizeof (MAP); <br/> for (INT I = 0; I <m; I ++) {<br/> scanf ("% d", & A, & B, & W ); <br/> map [a] [B] + = W; <br/> map [B] [a] + = W; <br/>}< br/> // print ans <br/> printf ("% d/N", mincut (n )); <br/>}< br/> return 0; <br/>}< br/>