Olivier Marty 8 years ago
parent
commit
5f04c30039
2 changed files with 25 additions and 0 deletions
  1. 22 0
      code/MST.cpp
  2. 3 0
      main.tex

+ 22 - 0
code/MST.cpp

@@ -0,0 +1,22 @@
+// Using Union-find
+struct edge{ int u,v,w; };
+bool Kruskal_cmp(const edge *a, const edge *b) {
+  return a->w<b->w;
+}
+// Return -1 if no tree found.
+int Kruskal(int n, int m, edge e[], int ret[]) {
+  if(n==1) return 0;
+  static edge *d[maxm];
+  for(int i=0; i<m; i++) d[i] = e+i;
+  sort(d, d+m, Kruskal_cmp);
+  int f[maxn], c=0;
+  make(f,i);
+  for(int i=0, j=0; i<m; i++)
+    if(find(f, d[i]->u) != find(f, d[i]->v)) {
+      unite(f,d[i]->u,d[i]->v);
+      c+=d[i]->w;
+      ret[j]=d[i]-e;
+      if(++j==n-1) return c;
+    }
+  return -1;
+}

+ 3 - 0
main.tex

@@ -159,6 +159,9 @@ Temps de cuisson : $O(n)$
 \subsection{Floyd-Warshall (all shortest path)}
 {\scriptsize\lstinputlisting{code/FloydWarshall.cpp}}
 
+\subsection{Minimum Spanning Tree -- Kruskal}
+{\scriptsize\lstinputlisting{code/MST.cpp}}
+
 \subsection{Strongly connected components}
 {\scriptsize\lstinputlisting{code/SCC.cc}}