/* -*- C++ -*- * demo/kruskal_demo.cc - Part of LEMON, a generic C++ optimization library * * Copyright (C) 2006 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport * (Egervary Research Group on Combinatorial Optimization, EGRES). * * Permission to use, modify and distribute this software is granted * provided that this copyright notice appears in all copies. For * precise terms see the accompanying LICENSE file. * * This software is provided "AS IS" with no warranty of any kind, * express or implied, and with no claim as to its suitability for any * purpose. * */ ///\ingroup demos ///\file ///\brief Minimum weight spanning tree by Kruskal algorithm (demo). /// /// This demo program shows how to find a minimum weight spanning tree /// in a graph by using the Kruskal algorithm. /// /// \include kruskal_demo.cc #include #include #include #include #include using namespace std; using namespace lemon; int main() { typedef ListGraph::Node Node; typedef ListGraph::Edge Edge; typedef ListGraph::NodeIt NodeIt; typedef ListGraph::EdgeIt EdgeIt; ListGraph g; //Make an example graph g. Node s=g.addNode(); Node v1=g.addNode(); Node v2=g.addNode(); Node v3=g.addNode(); Node v4=g.addNode(); Node t=g.addNode(); Edge e1 = g.addEdge(s, v1); Edge e2 = g.addEdge(s, v2); Edge e3 = g.addEdge(v1, v2); Edge e4 = g.addEdge(v2, v1); Edge e5 = g.addEdge(v1, v3); Edge e6 = g.addEdge(v3, v2); Edge e7 = g.addEdge(v2, v4); Edge e8 = g.addEdge(v4, v3); Edge e9 = g.addEdge(v3, t); Edge e10 = g.addEdge(v4, t); //Make the input for the kruskal. typedef ListGraph::EdgeMap ECostMap; ECostMap edge_cost_map(g); // Fill the edge_cost_map. edge_cost_map.set(e1, -10); edge_cost_map.set(e2, -9); edge_cost_map.set(e3, -8); edge_cost_map.set(e4, -7); edge_cost_map.set(e5, -6); edge_cost_map.set(e6, -5); edge_cost_map.set(e7, -4); edge_cost_map.set(e8, -3); edge_cost_map.set(e9, -2); edge_cost_map.set(e10, -1); // Make the map or the vector, which will contain the edges of the minimum // spanning tree. typedef ListGraph::EdgeMap EBoolMap; EBoolMap tree_map(g); vector tree_edge_vec; //Kruskal Algorithm. //Input: a graph (g); a costmap of the graph (edge_cost_map); a //boolmap (tree_map) or a vector (tree_edge_vec) to store the edges //of the output tree; //Output: it gives back the value of the minimum spanning tree, and //set true for the edges of the tree in the edgemap tree_map or //store the edges of the tree in the vector tree_edge_vec; // Kruskal with boolmap; std::cout << "The weight of the minimum spanning tree is " << kruskal(g, edge_cost_map, tree_map)<=0; i--) std::cout << g.id(tree_edge_vec[i]) << ";" ; std::cout << std::endl; std::cout << "The size of the tree again is: "<< tree_edge_vec.size() << std::endl; return 0; }