1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <set>
#include <limits>
using namespace std;
using NodeType = int;
struct Edge
{
NodeType dest;
double wt;
};
bool operator < ( Edge a, Edge b ) { return a.dest < b.dest; }
using Graph = map< NodeType, set<Edge> >;
//======================================================================
void read( istream &in, Graph &graph )
{
int n;
in >> n; // ignored in my code, as node number isn't fixed
NodeType a, b;
double wt;
while( in >> a >> b >> wt && !( a == 0 && b == 0 ) ) // messy
{
graph[a].insert( { b, wt } );
graph[b].insert( { a, wt } );
}
}
//======================================================================
void write( ostream &out, const Graph &graph )
{
for ( const auto &pr : graph )
{
for ( const Edge &edge : pr.second )
{
if ( pr.first < edge.dest ) out << pr.first << '\t' << edge.dest << '\t' << edge.wt << '\n';
}
}
}
//======================================================================
double dist( const Graph &graph )
{
double d = 0;
for ( const auto &pr : graph )
{
for ( const Edge &edge : pr.second )
{
if ( pr.first < edge.dest ) d += edge.wt;
}
}
return d;
}
//======================================================================
bool Prim( Graph &graph, Graph &MST )
{
MST.clear();
set<NodeType> available;
for ( auto &pr : graph ) available.insert( pr.first );
NodeType start = *available.begin();
available.erase( start );
MST[start] = {};
while( !available.empty() )
{
// Find shortest distance from a node in current MST to a node outside current MST
double minDist = numeric_limits<double>::max();
NodeType minNode;
Edge minEdge;
bool found = false;
for ( auto &pr : MST )
{
for ( Edge edge : graph[pr.first] )
{
if ( available.find( edge.dest ) != available.end() && edge.wt < minDist )
{
minNode = pr.first;
minEdge = edge;
minDist = edge.wt;
found = true;
}
}
}
if ( !found ) return false;
available.erase( minEdge.dest );
MST[minNode].insert( minEdge );
MST[minEdge.dest].insert( { minNode, minDist } );
}
return true;
}
//======================================================================
int main()
{
// ifstream in( "data.txt" );
istringstream in( "6 \n"
"1 2 4\n"
"1 3 2\n"
"1 5 3\n"
"2 4 5\n"
"3 4 1\n"
"3 5 6\n"
"3 6 3\n"
"4 6 6\n"
"5 6 2\n"
"0 0 0\n" );
Graph G;
read( in, G );
cout << "Original graph:\n";
write( cout, G );
Graph P;
if ( Prim( G, P ) )
{
cout << "\nMinimum spanning tree (size " << dist( P ) << ")\n";
write( cout, P );
}
}
|