mst.h
Go to the documentation of this file.
00001 /***
00002  Implementaion of minimum spanning tree
00003  ***/
00004 #ifndef  _MST_H
00005 #define  _MST_H
00006 #include "graph.h"
00007 #include <bitset>
00008 #include <climits>
00009 #include <algorithm>
00010 #include <cstdio>
00011 
00012 class MSTStrategy
00013 {
00014 public:
00015     virtual std::vector<graph::Vertex> mst(graph& g) = 0;
00016 
00017 protected:
00018 //      void printMST(std::vector<graph::Vertex>& parent, graph& g)
00019 //      {
00020 //              printf("Edge   Weight\n");
00021 //              for (auto i = 1; i < g.vertexCount(); i++)
00022 //                      printf("%d - %d    %d \n", parent[i], i, g[i][parent[i]]);
00023 //      }
00024 };
00025 
00026 class PrimeMST : public MSTStrategy
00027 {
00028 public:
00029     std::vector<graph::Vertex> mst(graph& g)
00030         {
00031                 std::vector<graph::Vertex> parent(g.vertexCount());
00032                 std::vector<graph::Weight> key(g.vertexCount());
00033                 std::vector<bool> mstSet(g.vertexCount());
00034 
00035                 for (auto i = 0; i < g.vertexCount(); ++i)
00036                 {
00037             key[i] = std::numeric_limits<graph::Vertex>::min();
00038                         mstSet[i] = false;
00039                 }
00040                 key[0] = 0;
00041                 parent[0] = -1;
00042 
00043                 for (int count = 0; count < g.vertexCount(); ++count)
00044                 {
00045             auto u = maxKey(key, mstSet, g.vertexCount());
00046                         mstSet[u] = true;
00047                         for (auto v = 0; v != g.vertexCount(); ++v)
00048                         {
00049                 if (g[u][v] && !mstSet[v] && g[u][v] > key[v])
00050                                 {
00051                                         parent[v] = u;
00052                                         key[v] = g[u][v];
00053                                 }
00054                         }
00055                 }
00056         return parent;
00057         //printMST(parent, g);
00058         }
00059 
00060 private:
00061     graph::Vertex maxKey(std::vector<graph::Weight>& key,
00062                                                  std::vector<bool>&     mstSet,
00063                                                  graph::Vertex vCount)
00064         {
00065         auto max = std::numeric_limits<graph::Vertex>::min();
00066         graph::Vertex max_index;
00067 
00068                 for (auto v = 0; v < vCount; v++)
00069             if (mstSet[v] == false && key[v] > max)
00070                 max = key[v], max_index = v;
00071 
00072         return max_index;
00073         }
00074 };
00075 
00076 #endif


tensor_field_nav_core
Author(s): Lintao Zheng, Kai Xu
autogenerated on Thu Jun 6 2019 19:50:56