3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
21 ///\brief Demonstrating the Dfs class with topological ordering
23 ///\include topological_ordering.cc
28 #include <lemon/list_graph.h>
29 #include <lemon/maps.h>
30 #include <lemon/dfs.h>
32 using namespace lemon;
35 template< typename GR >
36 class SerializingWriteMap
39 typedef typename GR::Node Key;
41 typedef std::list<Key> OrderedList;
45 SerializingWriteMap( const GR& ) {}
47 void set( const Key& k, const Value& v ) {
48 if( v ) order.push_front(k);
51 Value operator[] ( const Key& ) {
59 std::cout << "Topological Ordering demo" << std::endl;
61 // Create and build the graph
63 ListGraph::NodeMap<std::string> label(gr);
64 typedef ListGraph::Node Node;
66 // This DAG example for topological ordering is from the book New Algorithms
67 // (Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein)
69 Node belt = gr.addNode();
70 Node trousers = gr.addNode();
71 Node necktie = gr.addNode();
72 Node coat = gr.addNode();
73 Node socks = gr.addNode();
74 Node shirt = gr.addNode();
75 Node shoe = gr.addNode();
76 Node watch = gr.addNode();
77 Node pants = gr.addNode();
80 label[trousers] = "Trousers";
81 label[necktie] = "Necktie";
83 label[socks] = "Socks";
84 label[shirt] = "Shirt";
86 label[watch] = "Watch";
87 label[pants] = "Pants";
89 // Here we use a directed edge to indicate precedenc.
90 // The source must precede the target.
91 gr.addEdge( socks, shoe );
92 gr.addEdge( pants, shoe );
93 gr.addEdge( pants, trousers );
94 gr.addEdge( trousers, shoe );
95 gr.addEdge( trousers, belt );
96 gr.addEdge( belt, coat );
97 gr.addEdge( shirt, belt );
98 gr.addEdge( shirt, necktie );
99 gr.addEdge( necktie, coat );
102 // Calculate topological order
103 Dfs<ListGraph, Dfs<ListGraph>::DefProcessedMapTraits<SerializingWriteMap<ListGraph> > > dfs(gr);
104 SerializingWriteMap<ListGraph> list(gr);
105 dfs.processedMap(list);
108 // Write out the result
109 std::cout << "One possible order to dress up:";
110 for( SerializingWriteMap<ListGraph>::OrderedList::iterator it = list.order.begin(); it != list.order.end(); ++it )
111 std::cout << " " << label[*it];
112 std::cout << std::endl;