Changeset 209:765619b7cbb2 in lemon-main
- Timestamp:
- 07/13/08 20:51:02 (17 years ago)
- Branch:
- default
- Phase:
- public
- Files:
-
- 80 edited
Legend:
- Unmodified
- Added
- Removed
-
demo/arg_parser_demo.cc
r204 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 65 65 ap.other("infile", "The input file.") 66 66 .other("..."); 67 67 68 68 // Perform the parsing process 69 69 // (in case of any error it terminates the program) … … 85 85 if(ap.given("grb")) std::cout << " -grb is given\n"; 86 86 if(ap.given("grc")) std::cout << " -grc is given\n"; 87 87 88 88 switch(ap.files().size()) { 89 89 case 0: … … 95 95 default: 96 96 std::cout << " " 97 97 << ap.files().size() << " file arguments were given. They are:\n"; 98 98 } 99 99 for(unsigned int i=0;i<ap.files().size();++i) 100 100 std::cout << " '" << ap.files()[i] << "'\n"; 101 101 102 102 return 0; 103 103 } -
demo/graph_to_eps_demo.cc
r206 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 50 50 typedef ListDigraph::Arc Arc; 51 51 typedef dim2::Point<int> Point; 52 52 53 53 Node n1=g.addNode(); 54 54 Node n2=g.addNode(); … … 63 63 ListDigraph::ArcMap<int> acolors(g); 64 64 ListDigraph::ArcMap<int> widths(g); 65 65 66 66 coords[n1]=Point(50,50); sizes[n1]=1; colors[n1]=1; shapes[n1]=0; 67 67 coords[n2]=Point(50,70); sizes[n2]=2; colors[n2]=2; shapes[n2]=2; … … 69 69 coords[n4]=Point(70,50); sizes[n4]=2; colors[n4]=4; shapes[n4]=1; 70 70 coords[n5]=Point(85,60); sizes[n5]=3; colors[n5]=5; shapes[n5]=2; 71 71 72 72 Arc a; 73 73 … … 79 79 a=g.addArc(n2,n4); acolors[a]=1; widths[a]=2; 80 80 a=g.addArc(n3,n4); acolors[a]=2; widths[a]=1; 81 81 82 82 IdMap<ListDigraph,Node> id(g); 83 83 … … 183 183 ListDigraph::NodeMap<int> hcolors(h); 184 184 ListDigraph::NodeMap<Point> hcoords(h); 185 185 186 186 int cols=int(sqrt(double(palette.size()))); 187 187 for(int i=0;i<int(paletteW.size());i++) { … … 190 190 hcolors[n]=i; 191 191 } 192 192 193 193 cout << "Create 'graph_to_eps_demo_out_6_colors.eps'" << endl; 194 194 graphToEps(h,"graph_to_eps_demo_out_6_colors.eps"). … … 203 203 nodeColors(composeMap(paletteW,hcolors)). 204 204 run(); 205 205 206 206 return 0; 207 207 } -
demo/lgf_demo.cc
r193 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 22 22 /// 23 23 /// This program gives an example of how to read and write a digraph 24 /// and additional maps from/to a stream or a file using the 24 /// and additional maps from/to a stream or a file using the 25 25 /// \ref lgf-format "LGF" format. 26 26 /// … … 43 43 SmartDigraph::ArcMap<int> cap(g); 44 44 SmartDigraph::Node s, t; 45 45 46 46 try { 47 47 digraphReader("digraph.lgf", g). // read the directed graph into g -
doc/coding_style.dox
r41 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 19 19 /*! 20 20 21 \page coding_style LEMON Coding Style 21 \page coding_style LEMON Coding Style 22 22 23 23 \section naming_conv Naming Conventions … … 69 69 70 70 \code 71 AllWordsCapitalizedWithoutUnderscores 71 AllWordsCapitalizedWithoutUnderscores 72 72 \endcode 73 73 … … 77 77 78 78 \code 79 firstWordLowerCaseRestCapitalizedWithoutUnderscores 79 firstWordLowerCaseRestCapitalizedWithoutUnderscores 80 80 \endcode 81 81 … … 85 85 86 86 \code 87 ALL_UPPER_CASE_WITH_UNDERSCORES 87 ALL_UPPER_CASE_WITH_UNDERSCORES 88 88 \endcode 89 89 90 \subsection cs-loc-var Class and instance member variables, auto variables 90 \subsection cs-loc-var Class and instance member variables, auto variables 91 91 92 92 The names of class and instance member variables and auto variables (=variables used locally in methods) should look like the following. 93 93 94 94 \code 95 all_lower_case_with_underscores 95 all_lower_case_with_underscores 96 96 \endcode 97 97 -
doc/dirs.dox
r40 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 75 75 76 76 This directory contains some helper classes to implement graphs, maps and 77 some other classes. As a user you typically don't have to deal with these 77 some other classes. As a user you typically don't have to deal with these 78 78 files. 79 79 */ -
doc/groups.dox
r192 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 27 27 \brief Graph structures implemented in LEMON. 28 28 29 The implementation of combinatorial algorithms heavily relies on 30 efficient graph implementations. LEMON offers data structures which are 31 planned to be easily used in an experimental phase of implementation studies, 32 and thereafter the program code can be made efficient by small modifications. 29 The implementation of combinatorial algorithms heavily relies on 30 efficient graph implementations. LEMON offers data structures which are 31 planned to be easily used in an experimental phase of implementation studies, 32 and thereafter the program code can be made efficient by small modifications. 33 33 34 34 The most efficient implementation of diverse applications require the … … 41 41 some graph features like arc/edge or node deletion. 42 42 43 Alteration of standard containers need a very limited number of 44 operations, these together satisfy the everyday requirements. 45 In the case of graph structures, different operations are needed which do 46 not alter the physical graph, but gives another view. If some nodes or 43 Alteration of standard containers need a very limited number of 44 operations, these together satisfy the everyday requirements. 45 In the case of graph structures, different operations are needed which do 46 not alter the physical graph, but gives another view. If some nodes or 47 47 arcs have to be hidden or the reverse oriented graph have to be used, then 48 this is the case. It also may happen that in a flow implementation 49 the residual graph can be accessed by another algorithm, or a node-set 50 is to be shrunk for another algorithm. 51 LEMON also provides a variety of graphs for these requirements called 52 \ref graph_adaptors "graph adaptors". Adaptors cannot be used alone but only 53 in conjunction with other graph representations. 48 this is the case. It also may happen that in a flow implementation 49 the residual graph can be accessed by another algorithm, or a node-set 50 is to be shrunk for another algorithm. 51 LEMON also provides a variety of graphs for these requirements called 52 \ref graph_adaptors "graph adaptors". Adaptors cannot be used alone but only 53 in conjunction with other graph representations. 54 54 55 55 You are free to use the graph structure that fit your requirements 56 56 the best, most graph algorithms and auxiliary data structures can be used 57 with any graph structures. 57 with any graph structures. 58 58 */ 59 59 … … 64 64 65 65 This group describes some graph types between real graphs and graph adaptors. 66 These classes wrap graphs to give new functionality as the adaptors do it. 66 These classes wrap graphs to give new functionality as the adaptors do it. 67 67 On the other hand they are not light-weight structures as the adaptors. 68 68 */ 69 69 70 70 /** 71 @defgroup maps Maps 71 @defgroup maps Maps 72 72 @ingroup datas 73 73 \brief Map structures implemented in LEMON. … … 80 80 81 81 /** 82 @defgroup graph_maps Graph Maps 82 @defgroup graph_maps Graph Maps 83 83 @ingroup maps 84 84 \brief Special graph-related maps. … … 116 116 } 117 117 } 118 118 119 119 Digraph::NodeMap<int> degree_map(graph); 120 120 121 121 digraphToEps(graph, "graph.eps") 122 122 .coords(coords).scaleToA4().undirected() 123 123 .nodeColors(composeMap(functorToMap(nodeColor), degree_map)) 124 124 .run(); 125 \endcode 125 \endcode 126 126 The \c functorToMap() function makes an \c int to \c Color map from the 127 127 \e nodeColor() function. The \c composeMap() compose the \e degree_map … … 141 141 typedef DivMap<DoubleArcMap, DoubleArcMap> TimeMap; 142 142 TimeMap time(length, speed); 143 143 144 144 Dijkstra<Digraph, TimeMap> dijkstra(graph, time); 145 145 dijkstra.run(source, target); … … 153 153 154 154 /** 155 @defgroup matrices Matrices 155 @defgroup matrices Matrices 156 156 @ingroup datas 157 157 \brief Two dimensional data storages implemented in LEMON. … … 201 201 \brief Common graph search algorithms. 202 202 203 This group describes the common graph search algorithms like 203 This group describes the common graph search algorithms like 204 204 Breadth-first search (Bfs) and Depth-first search (Dfs). 205 205 */ … … 213 213 */ 214 214 215 /** 216 @defgroup max_flow Maximum Flow algorithms 217 @ingroup algs 215 /** 216 @defgroup max_flow Maximum Flow algorithms 217 @ingroup algs 218 218 \brief Algorithms for finding maximum flows. 219 219 … … 232 232 233 233 LEMON contains several algorithms for solving maximum flow problems: 234 - \ref lemon::EdmondsKarp "Edmonds-Karp" 234 - \ref lemon::EdmondsKarp "Edmonds-Karp" 235 235 - \ref lemon::Preflow "Goldberg's Preflow algorithm" 236 236 - \ref lemon::DinitzSleatorTarjan "Dinitz's blocking flow algorithm with dynamic trees" … … 251 251 252 252 This group describes the algorithms for finding minimum cost flows and 253 circulations. 254 */ 255 256 /** 257 @defgroup min_cut Minimum Cut algorithms 258 @ingroup algs 253 circulations. 254 */ 255 256 /** 257 @defgroup min_cut Minimum Cut algorithms 258 @ingroup algs 259 259 260 260 \brief Algorithms for finding minimum cut in graphs. … … 273 273 274 274 - \ref lemon::HaoOrlin "Hao-Orlin algorithm" to calculate minimum cut 275 in directed graphs 275 in directed graphs 276 276 - \ref lemon::NagamochiIbaraki "Nagamochi-Ibaraki algorithm" to 277 277 calculate minimum cut in undirected graphs … … 308 308 309 309 /** 310 @defgroup matching Matching algorithms 310 @defgroup matching Matching algorithms 311 311 @ingroup algs 312 312 \brief Algorithms for finding matchings in graphs and bipartite graphs. … … 315 315 matchings in graphs and bipartite graphs. The general matching problem is 316 316 finding a subset of the arcs which does not shares common endpoints. 317 317 318 318 There are several different algorithms for calculate matchings in 319 319 graphs. The matching problems in bipartite graphs are generally … … 324 324 325 325 Lemon contains the next algorithms: 326 - \ref lemon::MaxBipartiteMatching "MaxBipartiteMatching" Hopcroft-Karp 327 augmenting path algorithm for calculate maximum cardinality matching in 326 - \ref lemon::MaxBipartiteMatching "MaxBipartiteMatching" Hopcroft-Karp 327 augmenting path algorithm for calculate maximum cardinality matching in 328 328 bipartite graphs 329 - \ref lemon::PrBipartiteMatching "PrBipartiteMatching" Push-Relabel 330 algorithm for calculate maximum cardinality matching in bipartite graphs 331 - \ref lemon::MaxWeightedBipartiteMatching "MaxWeightedBipartiteMatching" 332 Successive shortest path algorithm for calculate maximum weighted matching 329 - \ref lemon::PrBipartiteMatching "PrBipartiteMatching" Push-Relabel 330 algorithm for calculate maximum cardinality matching in bipartite graphs 331 - \ref lemon::MaxWeightedBipartiteMatching "MaxWeightedBipartiteMatching" 332 Successive shortest path algorithm for calculate maximum weighted matching 333 333 and maximum weighted bipartite matching in bipartite graph 334 - \ref lemon::MinCostMaxBipartiteMatching "MinCostMaxBipartiteMatching" 335 Successive shortest path algorithm for calculate minimum cost maximum 334 - \ref lemon::MinCostMaxBipartiteMatching "MinCostMaxBipartiteMatching" 335 Successive shortest path algorithm for calculate minimum cost maximum 336 336 matching in bipartite graph 337 337 - \ref lemon::MaxMatching "MaxMatching" Edmond's blossom shrinking algorithm … … 397 397 */ 398 398 399 /** 400 @defgroup lp_utils Tools for Lp and Mip solvers 399 /** 400 @defgroup lp_utils Tools for Lp and Mip solvers 401 401 @ingroup lp_group 402 402 \brief Helper tools to the Lp and Mip solvers. … … 415 415 416 416 /** 417 @defgroup utils Tools and Utilities 417 @defgroup utils Tools and Utilities 418 418 \brief Tools and utilities for programming in LEMON 419 419 … … 468 468 \brief Graph Input-Output methods 469 469 470 This group describes the tools for importing and exporting graphs 470 This group describes the tools for importing and exporting graphs 471 471 and graph related data. Now it supports the LEMON format, the 472 472 \c DIMACS format and the encapsulated postscript (EPS) format. … … 487 487 488 488 This group describes general \c EPS drawing methods and special 489 graph exporting tools. 489 graph exporting tools. 490 490 */ 491 491 … … 499 499 500 500 The purpose of the classes in this group is fourfold. 501 501 502 502 - These classes contain the documentations of the concepts. In order 503 503 to avoid document multiplications, an implementation of a concept … … 552 552 @defgroup tools Standalone utility applications 553 553 554 Some utility applications are listed here. 554 Some utility applications are listed here. 555 555 556 556 The standard compilation procedure (<tt>./configure;make</tt>) will compile 557 them, as well. 558 */ 559 557 them, as well. 558 */ 559 -
doc/lgf.dox
r201 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 44 44 while a quoted token is a 45 45 character sequence surrounded by double quotes, and it can also 46 contain whitespaces and escape sequences. 46 contain whitespaces and escape sequences. 47 47 48 48 The \c \@nodes section describes a set of nodes and associated … … 73 73 \code 74 74 @arcs 75 75 capacity 76 76 1 2 16 77 77 1 3 12 -
doc/license.dox
r40 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
doc/mainpage.dox
r40 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 42 42 \subsection howtoread How to read the documentation 43 43 44 If you want to get a quick start and see the most important features then 44 If you want to get a quick start and see the most important features then 45 45 take a look at our \ref quicktour 46 46 "Quick Tour to LEMON" which will guide you along. 47 47 48 If you already feel like using our library, see the page that tells you 48 If you already feel like using our library, see the page that tells you 49 49 \ref getstart "How to start using LEMON". 50 50 51 If you 52 want to see how LEMON works, see 51 If you 52 want to see how LEMON works, see 53 53 some \ref demoprograms "demo programs"! 54 54 -
doc/namespaces.dox
r40 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
doc/template.h
r40 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
lemon/arg_parser.cc
r137 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 39 39 for(Opts::iterator i=_opts.begin();i!=_opts.end();++i) 40 40 if(i->second.self_delete) 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 } 60 41 switch(i->second.type) { 42 case BOOL: 43 delete i->second.bool_p; 44 break; 45 case STRING: 46 delete i->second.string_p; 47 break; 48 case DOUBLE: 49 delete i->second.double_p; 50 break; 51 case INTEGER: 52 delete i->second.int_p; 53 break; 54 case UNKNOWN: 55 break; 56 case FUNC: 57 break; 58 } 59 } 60 61 61 62 62 ArgParser &ArgParser::intOption(const std::string &name, 63 64 63 const std::string &help, 64 int value, bool obl) 65 65 { 66 66 ParData p; … … 75 75 76 76 ArgParser &ArgParser::doubleOption(const std::string &name, 77 78 77 const std::string &help, 78 double value, bool obl) 79 79 { 80 80 ParData p; … … 89 89 90 90 ArgParser &ArgParser::boolOption(const std::string &name, 91 92 91 const std::string &help, 92 bool value, bool obl) 93 93 { 94 94 ParData p; … … 103 103 104 104 ArgParser &ArgParser::stringOption(const std::string &name, 105 106 105 const std::string &help, 106 std::string value, bool obl) 107 107 { 108 108 ParData p; … … 117 117 118 118 ArgParser &ArgParser::refOption(const std::string &name, 119 120 119 const std::string &help, 120 int &ref, bool obl) 121 121 { 122 122 ParData p; … … 162 162 163 163 ArgParser &ArgParser::refOption(const std::string &name, 164 165 164 const std::string &help, 165 std::string &ref, bool obl) 166 166 { 167 167 ParData p; … … 176 176 177 177 ArgParser &ArgParser::funcOption(const std::string &name, 178 179 178 const std::string &help, 179 void (*func)(void *),void *data) 180 180 { 181 181 ParData p; … … 191 191 192 192 ArgParser &ArgParser::optionGroup(const std::string &group, 193 193 const std::string &opt) 194 194 { 195 195 Opts::iterator i = _opts.find(opt); 196 196 LEMON_ASSERT(i!=_opts.end(), "Unknown option: '"+opt+"'"); 197 LEMON_ASSERT(!(i->second.ingroup), 197 LEMON_ASSERT(!(i->second.ingroup), 198 198 "Option already in option group: '"+opt+"'"); 199 199 GroupData &g=_groups[group]; … … 211 211 212 212 ArgParser &ArgParser::synonym(const std::string &syn, 213 213 const std::string &opt) 214 214 { 215 215 Opts::iterator o = _opts.find(opt); … … 234 234 235 235 ArgParser &ArgParser::other(const std::string &name, 236 236 const std::string &help) 237 237 { 238 238 _others_help.push_back(OtherArg(name,help)); … … 245 245 if(i->second.has_syn) 246 246 for(Opts::iterator j=_opts.begin();j!=_opts.end();++j) 247 248 247 if(j->second.syn&&j->second.help==i->first) 248 os << "|-" << j->first; 249 249 switch(i->second.type) { 250 250 case STRING: … … 271 271 } 272 272 } 273 273 274 274 void ArgParser::showHelp(Opts::iterator i) 275 275 { … … 284 284 if(i->help.size()==0) return; 285 285 std::cerr << " " << i->name << std::endl 286 287 } 288 286 << " " << i->help << std::endl; 287 } 288 289 289 void ArgParser::shortHelp() 290 290 { … … 300 300 if(!g->second.mandatory) cstr << ']'; 301 301 if(pos+cstr.str().size()>LINE_LEN) { 302 303 302 std::cerr << std::endl << indent; 303 pos=indent.size(); 304 304 } 305 305 std::cerr << cstr.str(); … … 308 308 for(Opts::iterator i=_opts.begin();i!=_opts.end();++i) 309 309 if(!i->second.ingroup&&!i->second.syn) { 310 311 312 313 314 315 316 317 318 319 320 310 std::ostringstream cstr; 311 cstr << ' '; 312 if(!i->second.mandatory) cstr << '['; 313 show(cstr,i); 314 if(!i->second.mandatory) cstr << ']'; 315 if(pos+cstr.str().size()>LINE_LEN) { 316 std::cerr << std::endl << indent; 317 pos=indent.size(); 318 } 319 std::cerr << cstr.str(); 320 pos+=cstr.str().size(); 321 321 } 322 322 for(std::vector<OtherArg>::iterator i=_others_help.begin(); 323 323 i!=_others_help.end();++i) 324 324 { 325 326 327 328 329 330 331 332 333 325 std::ostringstream cstr; 326 cstr << ' ' << i->name; 327 328 if(pos+cstr.str().size()>LINE_LEN) { 329 std::cerr << std::endl << indent; 330 pos=indent.size(); 331 } 332 std::cerr << cstr.str(); 333 pos+=cstr.str().size(); 334 334 } 335 335 std::cerr << std::endl; 336 336 } 337 337 338 338 void ArgParser::showHelp() 339 339 { … … 341 341 std::cerr << "Where:\n"; 342 342 for(std::vector<OtherArg>::iterator i=_others_help.begin(); 343 343 i!=_others_help.end();++i) showHelp(i); 344 344 for(Opts::iterator i=_opts.begin();i!=_opts.end();++i) showHelp(i); 345 345 exit(1); 346 346 } 347 348 349 void ArgParser::unknownOpt(std::string arg) 347 348 349 void ArgParser::unknownOpt(std::string arg) 350 350 { 351 351 std::cerr << "\nUnknown option: " << arg << "\n"; … … 354 354 exit(1); 355 355 } 356 357 void ArgParser::requiresValue(std::string arg, OptType t) 356 357 void ArgParser::requiresValue(std::string arg, OptType t) 358 358 { 359 359 std::cerr << "Argument '" << arg << "' requires a"; … … 374 374 showHelp(); 375 375 } 376 376 377 377 378 378 void ArgParser::checkMandatories() … … 380 380 bool ok=true; 381 381 for(Opts::iterator i=_opts.begin();i!=_opts.end();++i) 382 if(i->second.mandatory&&!i->second.set) 383 384 385 std::cerr << _command_name 386 387 388 389 382 if(i->second.mandatory&&!i->second.set) 383 { 384 if(ok) 385 std::cerr << _command_name 386 << ": The following mandatory arguments are missing.\n"; 387 ok=false; 388 showHelp(i); 389 } 390 390 for(Groups::iterator i=_groups.begin();i!=_groups.end();++i) 391 391 if(i->second.mandatory||i->second.only_one) 392 393 394 395 396 397 398 std::cerr << _command_name 399 400 401 402 403 404 405 406 std::cerr << _command_name 407 408 409 410 411 412 413 392 { 393 int set=0; 394 for(GroupData::Opts::iterator o=i->second.opts.begin(); 395 o!=i->second.opts.end();++o) 396 if(_opts.find(*o)->second.set) ++set; 397 if(i->second.mandatory&&!set) { 398 std::cerr << _command_name 399 << ": At least one of the following arguments is mandatory.\n"; 400 ok=false; 401 for(GroupData::Opts::iterator o=i->second.opts.begin(); 402 o!=i->second.opts.end();++o) 403 showHelp(_opts.find(*o)); 404 } 405 if(i->second.only_one&&set>1) { 406 std::cerr << _command_name 407 << ": At most one of the following arguments can be given.\n"; 408 ok=false; 409 for(GroupData::Opts::iterator o=i->second.opts.begin(); 410 o!=i->second.opts.end();++o) 411 showHelp(_opts.find(*o)); 412 } 413 } 414 414 if(!ok) { 415 415 std::cerr << "\nType '" << _command_name << 416 416 " --help' to obtain a short summary on the usage.\n\n"; 417 417 exit(1); 418 418 } … … 424 424 std::string arg(_argv[ar]); 425 425 if (arg[0] != '-' || arg.size() == 1) { 426 426 _file_args.push_back(arg); 427 427 } 428 428 else { 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 429 Opts::iterator i = _opts.find(arg.substr(1)); 430 if(i==_opts.end()) unknownOpt(arg); 431 else { 432 if(i->second.syn) i=_opts.find(i->second.help); 433 ParData &p(i->second); 434 if (p.type==BOOL) *p.bool_p=true; 435 else if (p.type==FUNC) p.func_p.p(p.func_p.data); 436 else if(++ar==_argc) requiresValue(arg, p.type); 437 else { 438 std::string val(_argv[ar]); 439 std::istringstream vals(val); 440 switch(p.type) { 441 case STRING: 442 *p.string_p=val; 443 break; 444 case INTEGER: 445 vals >> *p.int_p; 446 break; 447 case DOUBLE: 448 vals >> *p.double_p; 449 break; 450 default: 451 break; 452 } 453 if(p.type!=STRING&&(!vals||!vals.eof())) 454 requiresValue(arg, p.type); 455 } 456 p.set = true; 457 } 458 458 } 459 459 } … … 461 461 462 462 return *this; 463 } 463 } 464 464 465 465 } -
lemon/arg_parser.h
r204 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 42 42 ///For a complete example see the \ref arg_parser_demo.cc demo file. 43 43 class ArgParser { 44 44 45 45 static void _showHelp(void *p); 46 46 protected: 47 47 48 48 int _argc; 49 49 const char **_argv; 50 50 51 51 enum OptType { UNKNOWN=0, BOOL=1, STRING=2, DOUBLE=3, INTEGER=4, FUNC=5 }; 52 52 53 53 class ParData { 54 54 public: 55 55 union { 56 57 58 59 60 61 62 63 64 56 bool *bool_p; 57 int *int_p; 58 double *double_p; 59 std::string *string_p; 60 struct { 61 void (*p)(void *); 62 void *data; 63 } func_p; 64 65 65 }; 66 66 std::string help; … … 73 73 bool self_delete; 74 74 ParData() : mandatory(false), type(UNKNOWN), set(false), ingroup(false), 75 75 has_syn(false), syn(false), self_delete(false) {} 76 76 }; 77 77 … … 79 79 Opts _opts; 80 80 81 class GroupData 81 class GroupData 82 82 { 83 83 public: … … 88 88 GroupData() :only_one(false), mandatory(false) {} 89 89 }; 90 90 91 91 typedef std::map<std::string,GroupData> Groups; 92 92 Groups _groups; … … 99 99 100 100 }; 101 101 102 102 std::vector<OtherArg> _others_help; 103 103 std::vector<std::string> _file_args; 104 104 std::string _command_name; 105 105 106 106 107 107 private: 108 108 //Bind a function to an option. … … 114 114 //\param data Data to be passed to \c func 115 115 ArgParser &funcOption(const std::string &name, 116 117 118 116 const std::string &help, 117 void (*func)(void *),void *data); 118 119 119 public: 120 120 … … 137 137 ///\param obl Indicate if the option is mandatory. 138 138 ArgParser &intOption(const std::string &name, 139 140 139 const std::string &help, 140 int value=0, bool obl=false); 141 141 142 142 ///Add a new floating point type option … … 148 148 ///\param obl Indicate if the option is mandatory. 149 149 ArgParser &doubleOption(const std::string &name, 150 151 150 const std::string &help, 151 double value=0, bool obl=false); 152 152 153 153 ///Add a new bool type option … … 160 160 ///\note A mandatory bool obtion is of very little use. 161 161 ArgParser &boolOption(const std::string &name, 162 163 162 const std::string &help, 163 bool value=false, bool obl=false); 164 164 165 165 ///Add a new string type option … … 171 171 ///\param obl Indicate if the option is mandatory. 172 172 ArgParser &stringOption(const std::string &name, 173 174 173 const std::string &help, 174 std::string value="", bool obl=false); 175 175 176 176 ///Give help string for non-parsed arguments. … … 180 180 ///\c help gives a more detailed description. 181 181 ArgParser &other(const std::string &name, 182 183 182 const std::string &help=""); 183 184 184 ///@} 185 185 … … 198 198 ///\retval ref The value of the argument will be written to this variable. 199 199 ArgParser &refOption(const std::string &name, 200 201 200 const std::string &help, 201 int &ref, bool obl=false); 202 202 203 203 ///Add a new floating type option with a storage reference … … 209 209 ///\retval ref The value of the argument will be written to this variable. 210 210 ArgParser &refOption(const std::string &name, 211 212 211 const std::string &help, 212 double &ref, bool obl=false); 213 213 214 214 ///Add a new bool type option with a storage reference … … 221 221 ///\note A mandatory bool obtion is of very little use. 222 222 ArgParser &refOption(const std::string &name, 223 224 223 const std::string &help, 224 bool &ref, bool obl=false); 225 225 226 226 ///Add a new string type option with a storage reference … … 232 232 ///\retval ref The value of the argument will be written to this variable. 233 233 ArgParser &refOption(const std::string &name, 234 235 236 234 const std::string &help, 235 std::string &ref, bool obl=false); 236 237 237 ///@} 238 238 239 239 ///\name Option Groups and Synonyms 240 240 /// 241 241 242 242 ///@{ 243 243 … … 249 249 ///\param opt The option name. 250 250 ArgParser &optionGroup(const std::string &group, 251 251 const std::string &opt); 252 252 253 253 ///Make the members of a group exclusive … … 256 256 ///given at the same time. 257 257 ArgParser &onlyOneGroup(const std::string &group); 258 258 259 259 ///Make a group mandatory 260 260 … … 262 262 ///must be given. 263 263 ArgParser &mandatoryGroup(const std::string &group); 264 264 265 265 ///Create synonym to an option 266 266 … … 268 268 ///option \c opt. 269 269 ArgParser &synonym(const std::string &syn, 270 271 270 const std::string &opt); 271 272 272 ///@} 273 273 … … 283 283 void requiresValue(std::string arg, OptType t); 284 284 void checkMandatories(); 285 285 286 286 ///Start the parsing process 287 287 ArgParser &parse(); 288 288 289 289 /// Synonym for parse() 290 ArgParser &run() 290 ArgParser &run() 291 291 { 292 292 return parse(); 293 293 } 294 294 295 295 ///Give back the command name (the 0th argument) 296 296 const std::string &commandName() { return _command_name; } 297 297 298 298 ///Check if an opion has been given to the command. 299 bool given(std::string op) 299 bool given(std::string op) 300 300 { 301 301 Opts::iterator i = _opts.find(op); … … 305 305 306 306 ///Magic type for operator[] 307 307 308 308 ///This is the type of the return value of ArgParser::operator[](). 309 309 ///It automatically converts to \c int, \c double, \c bool or 310 310 ///\c std::string if the type of the option matches, otherwise it 311 311 ///throws an exception (i.e. it performs runtime type checking). 312 class RefType 312 class RefType 313 313 { 314 314 ArgParser &_parser; … … 318 318 RefType(ArgParser &p,const std::string &n) :_parser(p),_name(n) {} 319 319 ///\e 320 operator bool() 320 operator bool() 321 321 { 322 323 324 325 326 327 322 Opts::iterator i = _parser._opts.find(_name); 323 LEMON_ASSERT(i!=_parser._opts.end(), 324 std::string()+"Unkown option: '"+_name+"'"); 325 LEMON_ASSERT(i->second.type==ArgParser::BOOL, 326 std::string()+"'"+_name+"' is a bool option"); 327 return *(i->second.bool_p); 328 328 } 329 329 ///\e 330 330 operator std::string() 331 331 { 332 333 334 335 336 337 332 Opts::iterator i = _parser._opts.find(_name); 333 LEMON_ASSERT(i!=_parser._opts.end(), 334 std::string()+"Unkown option: '"+_name+"'"); 335 LEMON_ASSERT(i->second.type==ArgParser::STRING, 336 std::string()+"'"+_name+"' is a string option"); 337 return *(i->second.string_p); 338 338 } 339 339 ///\e 340 operator double() 340 operator double() 341 341 { 342 343 344 345 346 347 348 349 342 Opts::iterator i = _parser._opts.find(_name); 343 LEMON_ASSERT(i!=_parser._opts.end(), 344 std::string()+"Unkown option: '"+_name+"'"); 345 LEMON_ASSERT(i->second.type==ArgParser::DOUBLE || 346 i->second.type==ArgParser::INTEGER, 347 std::string()+"'"+_name+"' is a floating point option"); 348 return i->second.type==ArgParser::DOUBLE ? 349 *(i->second.double_p) : *(i->second.int_p); 350 350 } 351 351 ///\e 352 operator int() 352 operator int() 353 353 { 354 355 356 357 358 359 354 Opts::iterator i = _parser._opts.find(_name); 355 LEMON_ASSERT(i!=_parser._opts.end(), 356 std::string()+"Unkown option: '"+_name+"'"); 357 LEMON_ASSERT(i->second.type==ArgParser::INTEGER, 358 std::string()+"'"+_name+"' is an integer option"); 359 return *(i->second.int_p); 360 360 } 361 361 … … 363 363 364 364 ///Give back the value of an option 365 365 366 366 ///Give back the value of an option. 367 367 ///\sa RefType … … 369 369 { 370 370 return RefType(*this, n); 371 } 371 } 372 372 373 373 ///Give back the non-option type arguments. … … 376 376 ///not starting with a '-' character. 377 377 std::vector<std::string> &files() { return _file_args; } 378 378 379 379 }; 380 380 } -
lemon/assert.h
r142 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 29 29 30 30 inline void assert_fail_log(const char *file, int line, const char *function, 31 31 const char *message, const char *assertion) 32 32 { 33 33 std::cerr << file << ":" << line << ": "; … … 41 41 42 42 inline void assert_fail_abort(const char *file, int line, 43 44 43 const char *function, const char* message, 44 const char *assertion) 45 45 { 46 46 assert_fail_log(file, line, function, message, assertion); … … 49 49 50 50 namespace _assert_bits { 51 52 51 52 53 53 inline const char* cstringify(const std::string& str) { 54 54 return str.c_str(); … … 57 57 inline const char* cstringify(const char* str) { 58 58 return str; 59 } 59 } 60 60 } 61 61 } … … 67 67 #undef LEMON_DEBUG 68 68 69 #if (defined(LEMON_ASSERT_LOG) ? 1 : 0) + 70 (defined(LEMON_ASSERT_ABORT) ? 1 : 0) + 69 #if (defined(LEMON_ASSERT_LOG) ? 1 : 0) + \ 70 (defined(LEMON_ASSERT_ABORT) ? 1 : 0) + \ 71 71 (defined(LEMON_ASSERT_CUSTOM) ? 1 : 0) > 1 72 72 #error "LEMON assertion system is not set properly" 73 73 #endif 74 74 75 #if ((defined(LEMON_ASSERT_LOG) ? 1 : 0) + 76 (defined(LEMON_ASSERT_ABORT) ? 1 : 0) + 77 (defined(LEMON_ASSERT_CUSTOM) ? 1 : 0) == 1 || 78 defined(LEMON_ENABLE_ASSERTS)) && 79 (defined(LEMON_DISABLE_ASSERTS) || 75 #if ((defined(LEMON_ASSERT_LOG) ? 1 : 0) + \ 76 (defined(LEMON_ASSERT_ABORT) ? 1 : 0) + \ 77 (defined(LEMON_ASSERT_CUSTOM) ? 1 : 0) == 1 || \ 78 defined(LEMON_ENABLE_ASSERTS)) && \ 79 (defined(LEMON_DISABLE_ASSERTS) || \ 80 80 defined(NDEBUG)) 81 81 #error "LEMON assertion system is not set properly" … … 137 137 /// \endcode 138 138 /// The checking is also disabled when the standard macro \c NDEBUG is defined. 139 /// 139 /// 140 140 /// The LEMON assertion system has a wide range of customization 141 141 /// properties. As a default behaviour the failed assertion prints a 142 142 /// short log message to the standard error and aborts the execution. 143 143 /// 144 /// The following modes can be used in the assertion system: 144 /// The following modes can be used in the assertion system: 145 145 /// 146 146 /// - \c LEMON_ASSERT_LOG The failed assertion prints a short log … … 156 156 /// \endcode 157 157 /// The name of the function should be defined as the \c 158 /// LEMON_CUSTOM_ASSERT_HANDLER macro name. 158 /// LEMON_CUSTOM_ASSERT_HANDLER macro name. 159 159 /// \code 160 160 /// #define LEMON_CUSTOM_ASSERT_HANDLER custom_assert_handler … … 167 167 /// \ref lemon/assert.h "assert.h" file is reincluded, then the 168 168 /// behaviour is changed appropiately to the new settings. 169 # define LEMON_ASSERT(exp, msg) 170 (static_cast<void> (!!(exp) ? 0 : ( 171 LEMON_ASSERT_HANDLER(__FILE__, __LINE__, 172 LEMON_FUNCTION_NAME,\173 169 # define LEMON_ASSERT(exp, msg) \ 170 (static_cast<void> (!!(exp) ? 0 : ( \ 171 LEMON_ASSERT_HANDLER(__FILE__, __LINE__, \ 172 LEMON_FUNCTION_NAME, \ 173 ::lemon::_assert_bits::cstringify(msg), #exp), 0))) 174 174 175 175 /// \ingroup exceptions … … 183 183 /// \endcode 184 184 /// 185 /// \see LEMON_ASSERT 186 # define LEMON_FIXME(msg) 187 (LEMON_ASSERT_HANDLER(__FILE__, __LINE__, LEMON_FUNCTION_NAME, 188 ::lemon::_assert_bits::cstringify(msg),\189 185 /// \see LEMON_ASSERT 186 # define LEMON_FIXME(msg) \ 187 (LEMON_ASSERT_HANDLER(__FILE__, __LINE__, LEMON_FUNCTION_NAME, \ 188 ::lemon::_assert_bits::cstringify(msg), \ 189 static_cast<const char*>(0))) 190 190 191 191 /// \ingroup exceptions … … 211 211 /// macro. 212 212 /// 213 /// \see LEMON_ASSERT 214 # define LEMON_DEBUG(exp, msg) 215 (static_cast<void> (!!(exp) ? 0 : ( 213 /// \see LEMON_ASSERT 214 # define LEMON_DEBUG(exp, msg) \ 215 (static_cast<void> (!!(exp) ? 0 : ( \ 216 216 LEMON_ASSERT_HANDLER(__FILE__, __LINE__, \ 217 LEMON_FUNCTION_NAME,\218 217 LEMON_FUNCTION_NAME, \ 218 ::lemon::_assert_bits::cstringify(msg), #exp), 0))) 219 219 220 220 #else … … 225 225 # define LEMON_DEBUG(exp, msg) (static_cast<void>(0)) 226 226 # else 227 # define LEMON_ASSERT(exp, msg) 228 (static_cast<void> (!!(exp) ? 0 : ( 227 # define LEMON_ASSERT(exp, msg) \ 228 (static_cast<void> (!!(exp) ? 0 : ( \ 229 229 LEMON_ASSERT_HANDLER(__FILE__, __LINE__, \ 230 LEMON_FUNCTION_NAME,\231 ::lemon::_assert_bits::cstringify(msg),\232 233 # define LEMON_FIXME(msg) 234 (LEMON_ASSERT_HANDLER(__FILE__, __LINE__, LEMON_FUNCTION_NAME, 235 ::lemon::_assert_bits::cstringify(msg),\236 230 LEMON_FUNCTION_NAME, \ 231 ::lemon::_assert_bits::cstringify(msg), \ 232 #exp), 0))) 233 # define LEMON_FIXME(msg) \ 234 (LEMON_ASSERT_HANDLER(__FILE__, __LINE__, LEMON_FUNCTION_NAME, \ 235 ::lemon::_assert_bits::cstringify(msg), \ 236 static_cast<const char*>(0))) 237 237 238 238 # if LEMON_ENABLE_DEBUG … … 241 241 LEMON_ASSERT_HANDLER(__FILE__, __LINE__, \ 242 242 LEMON_FUNCTION_NAME, \ 243 ::lemon::_assert_bits::cstringify(msg),\244 243 ::lemon::_assert_bits::cstringify(msg), \ 244 #exp), 0))) 245 245 # else 246 246 # define LEMON_DEBUG(exp, msg) (static_cast<void>(0)) -
lemon/base.cc
r49 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
lemon/bfs.h
r158 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 34 34 35 35 36 36 37 37 ///Default traits class of Bfs class. 38 38 … … 42 42 struct BfsDefaultTraits 43 43 { 44 ///The digraph type the algorithm runs on. 44 ///The digraph type the algorithm runs on. 45 45 typedef GR Digraph; 46 46 ///\brief The type of the map that stores the last 47 47 ///arcs of the shortest paths. 48 /// 48 /// 49 49 ///The type of the map that stores the last 50 50 ///arcs of the shortest paths. … … 53 53 typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap; 54 54 ///Instantiates a PredMap. 55 56 ///This function instantiates a \ref PredMap. 55 56 ///This function instantiates a \ref PredMap. 57 57 ///\param G is the digraph, to which we would like to define the PredMap. 58 58 ///\todo The digraph alone may be insufficient to initialize 59 static PredMap *createPredMap(const GR &G) 59 static PredMap *createPredMap(const GR &G) 60 60 { 61 61 return new PredMap(G); 62 62 } 63 63 ///The type of the map that indicates which nodes are processed. 64 64 65 65 ///The type of the map that indicates which nodes are processed. 66 66 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 68 68 typedef NullMap<typename Digraph::Node,bool> ProcessedMap; 69 69 ///Instantiates a ProcessedMap. 70 71 ///This function instantiates a \ref ProcessedMap. 70 71 ///This function instantiates a \ref ProcessedMap. 72 72 ///\param g is the digraph, to which 73 73 ///we would like to define the \ref ProcessedMap … … 81 81 } 82 82 ///The type of the map that indicates which nodes are reached. 83 83 84 84 ///The type of the map that indicates which nodes are reached. 85 85 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 87 87 typedef typename Digraph::template NodeMap<bool> ReachedMap; 88 88 ///Instantiates a ReachedMap. 89 90 ///This function instantiates a \ref ReachedMap. 89 90 ///This function instantiates a \ref ReachedMap. 91 91 ///\param G is the digraph, to which 92 92 ///we would like to define the \ref ReachedMap. … … 96 96 } 97 97 ///The type of the map that stores the dists of the nodes. 98 98 99 99 ///The type of the map that stores the dists of the nodes. 100 100 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 102 102 typedef typename Digraph::template NodeMap<int> DistMap; 103 103 ///Instantiates a DistMap. 104 105 ///This function instantiates a \ref DistMap. 104 105 ///This function instantiates a \ref DistMap. 106 106 ///\param G is the digraph, to which we would like to define the \ref DistMap 107 107 static DistMap *createDistMap(const GR &G) … … 110 110 } 111 111 }; 112 112 113 113 ///%BFS algorithm class. 114 114 115 115 ///\ingroup search 116 116 ///This class provides an efficient implementation of the %BFS algorithm. … … 127 127 #ifdef DOXYGEN 128 128 template <typename GR, 129 129 typename TR> 130 130 #else 131 131 template <typename GR=ListDigraph, 132 132 typename TR=BfsDefaultTraits<GR> > 133 133 #endif 134 134 class Bfs { … … 143 143 public: 144 144 virtual const char* what() const throw() { 145 145 return "lemon::Bfs::UninitializedParameter"; 146 146 } 147 147 }; … … 150 150 ///The type of the underlying digraph. 151 151 typedef typename TR::Digraph Digraph; 152 152 153 153 ///\brief The type of the map that stores the last 154 154 ///arcs of the shortest paths. … … 191 191 192 192 ///Creates the maps if necessary. 193 193 194 194 ///\todo Better memory allocation (instead of new). 195 void create_maps() 195 void create_maps() 196 196 { 197 197 if(!_pred) { 198 199 198 local_pred = true; 199 _pred = Traits::createPredMap(*G); 200 200 } 201 201 if(!_dist) { 202 203 202 local_dist = true; 203 _dist = Traits::createDistMap(*G); 204 204 } 205 205 if(!_reached) { 206 207 206 local_reached = true; 207 _reached = Traits::createReachedMap(*G); 208 208 } 209 209 if(!_processed) { 210 211 210 local_processed = true; 211 _processed = Traits::createProcessedMap(*G); 212 212 } 213 213 } 214 214 215 215 protected: 216 216 217 217 Bfs() {} 218 218 219 219 public: 220 220 221 221 typedef Bfs Create; 222 222 … … 228 228 struct DefPredMapTraits : public Traits { 229 229 typedef T PredMap; 230 static PredMap *createPredMap(const Digraph &) 230 static PredMap *createPredMap(const Digraph &) 231 231 { 232 232 throw UninitializedParameter(); 233 233 } 234 234 }; … … 239 239 /// 240 240 template <class T> 241 struct DefPredMap : public Bfs< Digraph, DefPredMapTraits<T> > { 241 struct DefPredMap : public Bfs< Digraph, DefPredMapTraits<T> > { 242 242 typedef Bfs< Digraph, DefPredMapTraits<T> > Create; 243 243 }; 244 244 245 245 template <class T> 246 246 struct DefDistMapTraits : public Traits { 247 247 typedef T DistMap; 248 static DistMap *createDistMap(const Digraph &) 248 static DistMap *createDistMap(const Digraph &) 249 249 { 250 250 throw UninitializedParameter(); 251 251 } 252 252 }; … … 257 257 /// 258 258 template <class T> 259 struct DefDistMap : public Bfs< Digraph, DefDistMapTraits<T> > { 259 struct DefDistMap : public Bfs< Digraph, DefDistMapTraits<T> > { 260 260 typedef Bfs< Digraph, DefDistMapTraits<T> > Create; 261 261 }; 262 262 263 263 template <class T> 264 264 struct DefReachedMapTraits : public Traits { 265 265 typedef T ReachedMap; 266 static ReachedMap *createReachedMap(const Digraph &) 266 static ReachedMap *createReachedMap(const Digraph &) 267 267 { 268 268 throw UninitializedParameter(); 269 269 } 270 270 }; … … 275 275 /// 276 276 template <class T> 277 struct DefReachedMap : public Bfs< Digraph, DefReachedMapTraits<T> > { 277 struct DefReachedMap : public Bfs< Digraph, DefReachedMapTraits<T> > { 278 278 typedef Bfs< Digraph, DefReachedMapTraits<T> > Create; 279 279 }; 280 280 281 281 template <class T> 282 282 struct DefProcessedMapTraits : public Traits { 283 283 typedef T ProcessedMap; 284 static ProcessedMap *createProcessedMap(const Digraph &) 284 static ProcessedMap *createProcessedMap(const Digraph &) 285 285 { 286 286 throw UninitializedParameter(); 287 287 } 288 288 }; … … 296 296 typedef Bfs< Digraph, DefProcessedMapTraits<T> > Create; 297 297 }; 298 298 299 299 struct DefDigraphProcessedMapTraits : public Traits { 300 300 typedef typename Digraph::template NodeMap<bool> ProcessedMap; 301 static ProcessedMap *createProcessedMap(const Digraph &G) 301 static ProcessedMap *createProcessedMap(const Digraph &G) 302 302 { 303 303 return new ProcessedMap(G); 304 304 } 305 305 }; … … 312 312 template <class T> 313 313 struct DefProcessedMapToBeDefaultMap : 314 public Bfs< Digraph, DefDigraphProcessedMapTraits> { 314 public Bfs< Digraph, DefDigraphProcessedMapTraits> { 315 315 typedef Bfs< Digraph, DefDigraphProcessedMapTraits> Create; 316 316 }; 317 317 318 318 ///@} 319 319 320 public: 321 320 public: 321 322 322 ///Constructor. 323 323 324 324 ///\param _G the digraph the algorithm will run on. 325 325 /// … … 331 331 _processed(NULL), local_processed(false) 332 332 { } 333 333 334 334 ///Destructor. 335 ~Bfs() 335 ~Bfs() 336 336 { 337 337 if(local_pred) delete _pred; … … 348 348 ///automatically allocated map, of course. 349 349 ///\return <tt> (*this) </tt> 350 Bfs &predMap(PredMap &m) 350 Bfs &predMap(PredMap &m) 351 351 { 352 352 if(local_pred) { 353 354 353 delete _pred; 354 local_pred=false; 355 355 } 356 356 _pred = &m; … … 365 365 ///automatically allocated map, of course. 366 366 ///\return <tt> (*this) </tt> 367 Bfs &reachedMap(ReachedMap &m) 367 Bfs &reachedMap(ReachedMap &m) 368 368 { 369 369 if(local_reached) { 370 371 370 delete _reached; 371 local_reached=false; 372 372 } 373 373 _reached = &m; … … 382 382 ///automatically allocated map, of course. 383 383 ///\return <tt> (*this) </tt> 384 Bfs &processedMap(ProcessedMap &m) 384 Bfs &processedMap(ProcessedMap &m) 385 385 { 386 386 if(local_processed) { 387 388 387 delete _processed; 388 local_processed=false; 389 389 } 390 390 _processed = &m; … … 399 399 ///automatically allocated map, of course. 400 400 ///\return <tt> (*this) </tt> 401 Bfs &distMap(DistMap &m) 401 Bfs &distMap(DistMap &m) 402 402 { 403 403 if(local_dist) { 404 405 404 delete _dist; 405 local_dist=false; 406 406 } 407 407 _dist = &m; … … 433 433 _curr_dist=1; 434 434 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) { 435 436 437 438 } 439 } 440 435 _pred->set(u,INVALID); 436 _reached->set(u,false); 437 _processed->set(u,false); 438 } 439 } 440 441 441 ///Adds a new source node. 442 442 … … 446 446 { 447 447 if(!(*_reached)[s]) 448 449 450 451 452 453 454 455 } 456 448 { 449 _reached->set(s,true); 450 _pred->set(s,INVALID); 451 _dist->set(s,0); 452 _queue[_queue_head++]=s; 453 _queue_next_dist=_queue_head; 454 } 455 } 456 457 457 ///Processes the next node. 458 458 … … 465 465 { 466 466 if(_queue_tail==_queue_next_dist) { 467 468 467 _curr_dist++; 468 _queue_next_dist=_queue_head; 469 469 } 470 470 Node n=_queue[_queue_tail++]; … … 472 472 Node m; 473 473 for(OutArcIt e(*G,n);e!=INVALID;++e) 474 475 476 477 478 479 474 if(!(*_reached)[m=G->target(e)]) { 475 _queue[_queue_head++]=m; 476 _reached->set(m,true); 477 _pred->set(m,e); 478 _dist->set(m,_curr_dist); 479 } 480 480 return n; 481 481 } … … 496 496 { 497 497 if(_queue_tail==_queue_next_dist) { 498 499 498 _curr_dist++; 499 _queue_next_dist=_queue_head; 500 500 } 501 501 Node n=_queue[_queue_tail++]; … … 503 503 Node m; 504 504 for(OutArcIt e(*G,n);e!=INVALID;++e) 505 506 507 508 509 505 if(!(*_reached)[m=G->target(e)]) { 506 _queue[_queue_head++]=m; 507 _reached->set(m,true); 508 _pred->set(m,e); 509 _dist->set(m,_curr_dist); 510 510 reach = reach || (target == m); 511 511 } 512 512 return n; 513 513 } … … 529 529 { 530 530 if(_queue_tail==_queue_next_dist) { 531 532 531 _curr_dist++; 532 _queue_next_dist=_queue_head; 533 533 } 534 534 Node n=_queue[_queue_tail++]; … … 536 536 Node m; 537 537 for(OutArcIt e(*G,n);e!=INVALID;++e) 538 539 540 541 542 543 544 538 if(!(*_reached)[m=G->target(e)]) { 539 _queue[_queue_head++]=m; 540 _reached->set(m,true); 541 _pred->set(m,e); 542 _dist->set(m,_curr_dist); 543 if (nm[m] && rnode == INVALID) rnode = m; 544 } 545 545 return n; 546 546 } 547 547 548 548 ///Next node to be processed. 549 549 … … 553 553 /// empty. 554 554 Node nextNode() 555 { 555 { 556 556 return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID; 557 557 } 558 558 559 559 ///\brief Returns \c false if there are nodes 560 560 ///to be processed in the queue … … 564 564 bool emptyQueue() { return _queue_tail==_queue_head; } 565 565 ///Returns the number of the nodes to be processed. 566 566 567 567 ///Returns the number of the nodes to be processed in the queue. 568 568 int queueSize() { return _queue_head-_queue_tail; } 569 569 570 570 ///Executes the algorithm. 571 571 … … 585 585 while ( !emptyQueue() ) processNextNode(); 586 586 } 587 587 588 588 ///Executes the algorithm until \c dest is reached. 589 589 … … 603 603 while ( !emptyQueue() && !reach ) processNextNode(dest, reach); 604 604 } 605 605 606 606 ///Executes the algorithm until a condition is met. 607 607 … … 622 622 Node rnode = INVALID; 623 623 while ( !emptyQueue() && rnode == INVALID ) { 624 624 processNextNode(nm, rnode); 625 625 } 626 626 return rnode; 627 627 } 628 628 629 629 ///Runs %BFS algorithm from node \c s. 630 630 631 631 ///This method runs the %BFS algorithm from a root node \c s 632 632 ///in order to … … 647 647 start(); 648 648 } 649 649 650 650 ///Finds the shortest path between \c s and \c t. 651 651 652 652 ///Finds the shortest path between \c s and \c t. 653 653 /// … … 667 667 return reached(t) ? _curr_dist : 0; 668 668 } 669 669 670 670 ///@} 671 671 … … 675 675 ///Before the use of these functions, 676 676 ///either run() or start() must be calleb. 677 677 678 678 ///@{ 679 679 … … 681 681 682 682 ///Gives back the shortest path. 683 683 684 684 ///Gives back the shortest path. 685 685 ///\pre The \c t should be reachable from the source. 686 Path path(Node t) 686 Path path(Node t) 687 687 { 688 688 return Path(*G, *_pred, t); … … 723 723 ///using this function. 724 724 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID: 725 726 725 G->source((*_pred)[v]); } 726 727 727 ///Returns a reference to the NodeMap of distances. 728 728 … … 731 731 ///be called before using this function. 732 732 const DistMap &distMap() const { return *_dist;} 733 733 734 734 ///Returns a reference to the shortest path tree map. 735 735 … … 739 739 ///must be called before using this function. 740 740 const PredMap &predMap() const { return *_pred;} 741 741 742 742 ///Checks if a node is reachable from the root. 743 743 … … 748 748 /// 749 749 bool reached(Node v) { return (*_reached)[v]; } 750 750 751 751 ///@} 752 752 }; … … 759 759 struct BfsWizardDefaultTraits 760 760 { 761 ///The digraph type the algorithm runs on. 761 ///The digraph type the algorithm runs on. 762 762 typedef GR Digraph; 763 763 ///\brief The type of the map that stores the last 764 764 ///arcs of the shortest paths. 765 /// 765 /// 766 766 ///The type of the map that stores the last 767 767 ///arcs of the shortest paths. … … 770 770 typedef NullMap<typename Digraph::Node,typename GR::Arc> PredMap; 771 771 ///Instantiates a PredMap. 772 773 ///This function instantiates a \ref PredMap. 772 773 ///This function instantiates a \ref PredMap. 774 774 ///\param g is the digraph, to which we would like to define the PredMap. 775 775 ///\todo The digraph alone may be insufficient to initialize 776 776 #ifdef DOXYGEN 777 static PredMap *createPredMap(const GR &g) 777 static PredMap *createPredMap(const GR &g) 778 778 #else 779 static PredMap *createPredMap(const GR &) 779 static PredMap *createPredMap(const GR &) 780 780 #endif 781 781 { … … 784 784 785 785 ///The type of the map that indicates which nodes are processed. 786 786 787 787 ///The type of the map that indicates which nodes are processed. 788 788 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 790 790 typedef NullMap<typename Digraph::Node,bool> ProcessedMap; 791 791 ///Instantiates a ProcessedMap. 792 793 ///This function instantiates a \ref ProcessedMap. 792 793 ///This function instantiates a \ref ProcessedMap. 794 794 ///\param g is the digraph, to which 795 795 ///we would like to define the \ref ProcessedMap … … 803 803 } 804 804 ///The type of the map that indicates which nodes are reached. 805 805 806 806 ///The type of the map that indicates which nodes are reached. 807 807 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 809 809 typedef typename Digraph::template NodeMap<bool> ReachedMap; 810 810 ///Instantiates a ReachedMap. 811 812 ///This function instantiates a \ref ReachedMap. 811 812 ///This function instantiates a \ref ReachedMap. 813 813 ///\param G is the digraph, to which 814 814 ///we would like to define the \ref ReachedMap. … … 818 818 } 819 819 ///The type of the map that stores the dists of the nodes. 820 820 821 821 ///The type of the map that stores the dists of the nodes. 822 822 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 824 824 typedef NullMap<typename Digraph::Node,int> DistMap; 825 825 ///Instantiates a DistMap. 826 827 ///This function instantiates a \ref DistMap. 826 827 ///This function instantiates a \ref DistMap. 828 828 ///\param g is the digraph, to which we would like to define the \ref DistMap 829 829 #ifdef DOXYGEN … … 836 836 } 837 837 }; 838 838 839 839 /// Default traits used by \ref BfsWizard 840 840 … … 866 866 ///Pointer to the source node. 867 867 Node _source; 868 868 869 869 public: 870 870 /// Constructor. 871 871 872 872 /// This constructor does not require parameters, therefore it initiates 873 873 /// all of the attributes to default values (0, INVALID). 874 874 BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0), 875 875 _dist(0), _source(INVALID) {} 876 876 877 877 /// Constructor. 878 878 879 879 /// This constructor requires some parameters, 880 880 /// listed in the parameters list. … … 883 883 /// \param s is the initial value of \ref _source 884 884 BfsWizardBase(const GR &g, Node s=INVALID) : 885 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))), 885 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))), 886 886 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {} 887 887 888 888 }; 889 889 890 890 /// A class to make the usage of Bfs algorithm easier 891 891 … … 922 922 //\e 923 923 typedef typename Digraph::OutArcIt OutArcIt; 924 924 925 925 ///\brief The type of the map that stores 926 926 ///the reached nodes … … 952 952 953 953 ///Runs Bfs algorithm from a given node. 954 954 955 955 ///Runs Bfs algorithm from a given node. 956 956 ///The node can be given by the \ref source function. … … 960 960 Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g)); 961 961 if(Base::_reached) 962 963 if(Base::_processed) 962 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached)); 963 if(Base::_processed) 964 964 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); 965 if(Base::_pred) 965 if(Base::_pred) 966 966 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); 967 if(Base::_dist) 967 if(Base::_dist) 968 968 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); 969 969 alg.run(Base::_source); … … 986 986 DefPredMapBase(const TR &b) : TR(b) {} 987 987 }; 988 988 989 989 ///\brief \ref named-templ-param "Named parameter" 990 990 ///function for setting PredMap … … 994 994 /// 995 995 template<class T> 996 BfsWizard<DefPredMapBase<T> > predMap(const T &t) 996 BfsWizard<DefPredMapBase<T> > predMap(const T &t) 997 997 { 998 998 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); 999 999 return BfsWizard<DefPredMapBase<T> >(*this); 1000 1000 } 1001 1002 1001 1002 1003 1003 template<class T> 1004 1004 struct DefReachedMapBase : public Base { … … 1007 1007 DefReachedMapBase(const TR &b) : TR(b) {} 1008 1008 }; 1009 1009 1010 1010 ///\brief \ref named-templ-param "Named parameter" 1011 1011 ///function for setting ReachedMap … … 1015 1015 /// 1016 1016 template<class T> 1017 BfsWizard<DefReachedMapBase<T> > reachedMap(const T &t) 1017 BfsWizard<DefReachedMapBase<T> > reachedMap(const T &t) 1018 1018 { 1019 1019 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t)); 1020 1020 return BfsWizard<DefReachedMapBase<T> >(*this); 1021 1021 } 1022 1022 1023 1023 1024 1024 template<class T> … … 1028 1028 DefProcessedMapBase(const TR &b) : TR(b) {} 1029 1029 }; 1030 1030 1031 1031 ///\brief \ref named-templ-param "Named parameter" 1032 1032 ///function for setting ProcessedMap … … 1036 1036 /// 1037 1037 template<class T> 1038 BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t) 1038 BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t) 1039 1039 { 1040 1040 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t)); 1041 1041 return BfsWizard<DefProcessedMapBase<T> >(*this); 1042 1042 } 1043 1044 1043 1044 1045 1045 template<class T> 1046 1046 struct DefDistMapBase : public Base { … … 1049 1049 DefDistMapBase(const TR &b) : TR(b) {} 1050 1050 }; 1051 1051 1052 1052 ///\brief \ref named-templ-param "Named parameter" 1053 1053 ///function for setting DistMap type … … 1057 1057 /// 1058 1058 template<class T> 1059 BfsWizard<DefDistMapBase<T> > distMap(const T &t) 1059 BfsWizard<DefDistMapBase<T> > distMap(const T &t) 1060 1060 { 1061 1061 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); 1062 1062 return BfsWizard<DefDistMapBase<T> >(*this); 1063 1063 } 1064 1064 1065 1065 /// Sets the source node, from which the Bfs algorithm runs. 1066 1066 1067 1067 /// Sets the source node, from which the Bfs algorithm runs. 1068 1068 /// \param s is the source node. 1069 BfsWizard<TR> &source(Node s) 1069 BfsWizard<TR> &source(Node s) 1070 1070 { 1071 1071 Base::_source=s; 1072 1072 return *this; 1073 1073 } 1074 1074 1075 1075 }; 1076 1076 1077 1077 ///Function type interface for Bfs algorithm. 1078 1078 … … 1101 1101 #ifdef DOXYGEN 1102 1102 /// \brief Visitor class for bfs. 1103 /// 1103 /// 1104 1104 /// This class defines the interface of the BfsVisit events, and 1105 1105 /// it could be the base of a real Visitor class. … … 1110 1110 typedef typename Digraph::Node Node; 1111 1111 /// \brief Called when the arc reach a node. 1112 /// 1112 /// 1113 1113 /// It is called when the bfs find an arc which target is not 1114 1114 /// reached yet. 1115 1115 void discover(const Arc& arc) {} 1116 1116 /// \brief Called when the node reached first time. 1117 /// 1117 /// 1118 1118 /// It is Called when the node reached first time. 1119 1119 void reach(const Node& node) {} 1120 /// \brief Called when the arc examined but target of the arc 1120 /// \brief Called when the arc examined but target of the arc 1121 1121 /// already discovered. 1122 /// 1123 /// It called when the arc examined but the target of the arc 1122 /// 1123 /// It called when the arc examined but the target of the arc 1124 1124 /// already discovered. 1125 1125 void examine(const Arc& arc) {} 1126 1126 /// \brief Called for the source node of the bfs. 1127 /// 1127 /// 1128 1128 /// It is called for the source node of the bfs. 1129 1129 void start(const Node& node) {} 1130 1130 /// \brief Called when the node processed. 1131 /// 1131 /// 1132 1132 /// It is Called when the node processed. 1133 1133 void process(const Node& node) {} … … 1148 1148 struct Constraints { 1149 1149 void constraints() { 1150 1151 1152 1153 1154 1155 1150 Arc arc; 1151 Node node; 1152 visitor.discover(arc); 1153 visitor.reach(node); 1154 visitor.examine(arc); 1155 visitor.start(node); 1156 1156 visitor.process(node); 1157 1157 } … … 1168 1168 struct BfsVisitDefaultTraits { 1169 1169 1170 /// \brief The digraph type the algorithm runs on. 1170 /// \brief The digraph type the algorithm runs on. 1171 1171 typedef _Digraph Digraph; 1172 1172 1173 1173 /// \brief The type of the map that indicates which nodes are reached. 1174 /// 1174 /// 1175 1175 /// The type of the map that indicates which nodes are reached. 1176 1176 /// It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 1180 1180 /// \brief Instantiates a ReachedMap. 1181 1181 /// 1182 /// This function instantiates a \ref ReachedMap. 1182 /// This function instantiates a \ref ReachedMap. 1183 1183 /// \param digraph is the digraph, to which 1184 1184 /// we would like to define the \ref ReachedMap. … … 1190 1190 1191 1191 /// \ingroup search 1192 /// 1192 /// 1193 1193 /// \brief %BFS Visit algorithm class. 1194 /// 1194 /// 1195 1195 /// This class provides an efficient implementation of the %BFS algorithm 1196 1196 /// with visitor interface. … … 1198 1198 /// The %BfsVisit class provides an alternative interface to the Bfs 1199 1199 /// class. It works with callback mechanism, the BfsVisit object calls 1200 /// on every bfs event the \c Visitor class member functions. 1200 /// on every bfs event the \c Visitor class member functions. 1201 1201 /// 1202 1202 /// \tparam _Digraph The digraph type the algorithm runs on. The default value is 1203 1203 /// \ref ListDigraph. The value of _Digraph is not used directly by Bfs, it 1204 1204 /// is only passed to \ref BfsDefaultTraits. 1205 /// \tparam _Visitor The Visitor object for the algorithm. The 1205 /// \tparam _Visitor The Visitor object for the algorithm. The 1206 1206 /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty Visitor which 1207 1207 /// does not observe the Bfs events. If you want to observe the bfs 1208 1208 /// events you should implement your own Visitor class. 1209 /// \tparam _Traits Traits class to set various data types used by the 1209 /// \tparam _Traits Traits class to set various data types used by the 1210 1210 /// algorithm. The default traits class is 1211 1211 /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>". … … 1216 1216 #else 1217 1217 template <typename _Digraph = ListDigraph, 1218 1219 1218 typename _Visitor = BfsVisitor<_Digraph>, 1219 typename _Traits = BfsDefaultTraits<_Digraph> > 1220 1220 #endif 1221 1221 class BfsVisit { 1222 1222 public: 1223 1223 1224 1224 /// \brief \ref Exception for uninitialized parameters. 1225 1225 /// … … 1228 1228 class UninitializedParameter : public lemon::UninitializedParameter { 1229 1229 public: 1230 virtual const char* what() const throw() 1230 virtual const char* what() const throw() 1231 1231 { 1232 1232 return "lemon::BfsVisit::UninitializedParameter"; 1233 1233 } 1234 1234 }; … … 1267 1267 void create_maps() { 1268 1268 if(!_reached) { 1269 1270 1269 local_reached = true; 1270 _reached = Traits::createReachedMap(*_digraph); 1271 1271 } 1272 1272 } … … 1275 1275 1276 1276 BfsVisit() {} 1277 1277 1278 1278 public: 1279 1279 … … 1287 1287 typedef T ReachedMap; 1288 1288 static ReachedMap *createReachedMap(const Digraph &digraph) { 1289 1290 } 1291 }; 1292 /// \brief \ref named-templ-param "Named parameter" for setting 1289 throw UninitializedParameter(); 1290 } 1291 }; 1292 /// \brief \ref named-templ-param "Named parameter" for setting 1293 1293 /// ReachedMap type 1294 1294 /// … … 1296 1296 template <class T> 1297 1297 struct DefReachedMap : public BfsVisit< Digraph, Visitor, 1298 1298 DefReachedMapTraits<T> > { 1299 1299 typedef BfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create; 1300 1300 }; 1301 1301 ///@} 1302 1302 1303 public: 1304 1303 public: 1304 1305 1305 /// \brief Constructor. 1306 1306 /// … … 1310 1310 /// \param visitor The visitor of the algorithm. 1311 1311 /// 1312 BfsVisit(const Digraph& digraph, Visitor& visitor) 1312 BfsVisit(const Digraph& digraph, Visitor& visitor) 1313 1313 : _digraph(&digraph), _visitor(&visitor), 1314 1315 1314 _reached(0), local_reached(false) {} 1315 1316 1316 /// \brief Destructor. 1317 1317 /// … … 1330 1330 BfsVisit &reachedMap(ReachedMap &m) { 1331 1331 if(local_reached) { 1332 1333 1332 delete _reached; 1333 local_reached = false; 1334 1334 } 1335 1335 _reached = &m; … … 1358 1358 _list_front = _list_back = -1; 1359 1359 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) { 1360 1361 } 1362 } 1363 1360 _reached->set(u, false); 1361 } 1362 } 1363 1364 1364 /// \brief Adds a new source node. 1365 1365 /// … … 1367 1367 void addSource(Node s) { 1368 1368 if(!(*_reached)[s]) { 1369 1370 1371 1369 _reached->set(s,true); 1370 _visitor->start(s); 1371 _visitor->reach(s); 1372 1372 _list[++_list_back] = s; 1373 1374 } 1375 1373 } 1374 } 1375 1376 1376 /// \brief Processes the next node. 1377 1377 /// … … 1381 1381 /// 1382 1382 /// \pre The queue must not be empty! 1383 Node processNextNode() { 1383 Node processNextNode() { 1384 1384 Node n = _list[++_list_front]; 1385 1385 _visitor->process(n); … … 1468 1468 /// \return The next node to be processed or INVALID if the stack is 1469 1469 /// empty. 1470 Node nextNode() { 1470 Node nextNode() { 1471 1471 return _list_front != _list_back ? _list[_list_front + 1] : INVALID; 1472 1472 } … … 1483 1483 /// Returns the number of the nodes to be processed in the queue. 1484 1484 int queueSize() { return _list_back - _list_front; } 1485 1485 1486 1486 /// \brief Executes the algorithm. 1487 1487 /// … … 1493 1493 while ( !emptyQueue() ) processNextNode(); 1494 1494 } 1495 1495 1496 1496 /// \brief Executes the algorithm until \c dest is reached. 1497 1497 /// … … 1504 1504 while ( !emptyQueue() && !reach ) processNextNode(dest, reach); 1505 1505 } 1506 1506 1507 1507 /// \brief Executes the algorithm until a condition is met. 1508 1508 /// … … 1522 1522 Node rnode = INVALID; 1523 1523 while ( !emptyQueue() && rnode == INVALID ) { 1524 1524 processNextNode(nm, rnode); 1525 1525 } 1526 1526 return rnode; … … 1543 1543 1544 1544 /// \brief Runs %BFSVisit algorithm to visit all nodes in the digraph. 1545 /// 1545 /// 1546 1546 /// This method runs the %BFS algorithm in order to 1547 1547 /// compute the %BFS path to each node. The algorithm computes -
lemon/bin_heap.h
r157 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 49 49 ///\sa Dijkstra 50 50 template <typename _Prio, typename _ItemIntMap, 51 51 typename _Compare = std::less<_Prio> > 52 52 class BinHeap { 53 53 … … 91 91 /// should be PRE_HEAP (-1) for each element. 92 92 explicit BinHeap(ItemIntMap &_iim) : iim(_iim) {} 93 93 94 94 /// \brief The constructor. 95 95 /// … … 100 100 /// 101 101 /// \param _comp The comparator function object. 102 BinHeap(ItemIntMap &_iim, const Compare &_comp) 102 BinHeap(ItemIntMap &_iim, const Compare &_comp) 103 103 : iim(_iim), comp(_comp) {} 104 104 … … 108 108 /// \brief Returns the number of items stored in the heap. 109 109 int size() const { return data.size(); } 110 110 111 111 /// \brief Checks if the heap stores no items. 112 112 /// … … 115 115 116 116 /// \brief Make empty this heap. 117 /// 117 /// 118 118 /// Make empty this heap. It does not change the cross reference map. 119 119 /// If you want to reuse what is not surely empty you should first clear 120 120 /// the heap and after that you should set the cross reference map for 121 121 /// each item to \c PRE_HEAP. 122 void clear() { 123 data.clear(); 122 void clear() { 123 data.clear(); 124 124 } 125 125 … … 135 135 int par = parent(hole); 136 136 while( hole>0 && less(p,data[par]) ) { 137 138 139 137 move(data[par],hole); 138 hole = par; 139 par = parent(hole); 140 140 } 141 141 move(p, hole); … … 146 146 int child = second_child(hole); 147 147 while(child < length) { 148 149 150 151 152 153 154 155 148 if( less(data[child-1], data[child]) ) { 149 --child; 150 } 151 if( !less(data[child], p) ) 152 goto ok; 153 move(data[child], hole); 154 hole = child; 155 child = second_child(hole); 156 156 } 157 157 child--; 158 158 if( child<length && less(data[child], p) ) { 159 160 159 move(data[child], hole); 160 hole=child; 161 161 } 162 162 ok: … … 182 182 183 183 /// \brief Insert an item into the heap with the given heap. 184 /// 185 /// Adds \c i to the heap with priority \c p. 184 /// 185 /// Adds \c i to the heap with priority \c p. 186 186 /// \param i The item to insert. 187 187 /// \param p The priority of the item. … … 191 191 /// 192 192 /// This method returns the item with minimum priority relative to \c 193 /// Compare. 194 /// \pre The heap must be nonempty. 193 /// Compare. 194 /// \pre The heap must be nonempty. 195 195 Item top() const { 196 196 return data[0].first; … … 208 208 /// 209 209 /// This method deletes the item with minimum priority relative to \c 210 /// Compare from the heap. 211 /// \pre The heap must be non-empty. 210 /// Compare from the heap. 211 /// \pre The heap must be non-empty. 212 212 void pop() { 213 213 int n = data.size()-1; 214 214 iim.set(data[0].first, POST_HEAP); 215 215 if (n > 0) { 216 216 bubble_down(0, data[n], n); 217 217 } 218 218 data.pop_back(); … … 229 229 iim.set(data[h].first, POST_HEAP); 230 230 if( h < n ) { 231 232 233 231 if ( bubble_up(h, data[n]) == h) { 232 bubble_down(h, data[n], n); 233 } 234 234 } 235 235 data.pop_back(); 236 236 } 237 237 238 238 239 239 /// \brief Returns the priority of \c i. 240 240 /// 241 /// This function returns the priority of item \c i. 241 /// This function returns the priority of item \c i. 242 242 /// \pre \c i must be in the heap. 243 243 /// \param i The item. … … 247 247 } 248 248 249 /// \brief \c i gets to the heap with priority \c p independently 249 /// \brief \c i gets to the heap with priority \c p independently 250 250 /// if \c i was already there. 251 251 /// … … 257 257 int idx = iim[i]; 258 258 if( idx < 0 ) { 259 259 push(i,p); 260 260 } 261 261 else if( comp(p, data[idx].second) ) { 262 262 bubble_up(idx, Pair(i,p)); 263 263 } 264 264 else { 265 265 bubble_down(idx, Pair(i,p), data.size()); 266 266 } 267 267 } … … 278 278 bubble_up(idx, Pair(i,p)); 279 279 } 280 280 281 281 /// \brief Increases the priority of \c i to \c p. 282 282 /// 283 /// This method sets the priority of item \c i to \c p. 283 /// This method sets the priority of item \c i to \c p. 284 284 /// \pre \c i must be stored in the heap with priority at most \c 285 285 /// p relative to \c Compare. … … 291 291 } 292 292 293 /// \brief Returns if \c item is in, has already been in, or has 293 /// \brief Returns if \c item is in, has already been in, or has 294 294 /// never been in the heap. 295 295 /// … … 302 302 int s = iim[i]; 303 303 if( s>=0 ) 304 304 s=0; 305 305 return State(s); 306 306 } … … 312 312 /// better time complexity. 313 313 /// \param i The item. 314 /// \param st The state. It should not be \c IN_HEAP. 314 /// \param st The state. It should not be \c IN_HEAP. 315 315 void state(const Item& i, State st) { 316 316 switch (st) { … … 341 341 342 342 }; // class BinHeap 343 343 344 344 } // namespace lemon 345 345 -
lemon/bits/alteration_notifier.h
r157 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 33 33 /// \ingroup graphbits 34 34 /// 35 /// \brief Notifier class to notify observes about alterations in 35 /// \brief Notifier class to notify observes about alterations in 36 36 /// a container. 37 37 /// … … 50 50 /// alteration of the graph. 51 51 /// 52 /// This class provides an interface to the container. The \e first() and \e 52 /// This class provides an interface to the container. The \e first() and \e 53 53 /// next() member functions make possible to iterate on the keys of the 54 54 /// container. The \e id() function returns an integer id for each key. … … 61 61 /// from the graph. If all items are erased from the graph or from an empty 62 62 /// graph a new graph is builded then it can be signaled with the 63 /// clear() and build() members. Important rule that if we erase items 63 /// clear() and build() members. Important rule that if we erase items 64 64 /// from graph we should first signal the alteration and after that erase 65 65 /// them from the container, on the other way on item addition we should … … 69 69 /// \e ObserverBase nested class. The signals can be handled with 70 70 /// overriding the virtual functions defined in the base class. The 71 /// observer base can be attached to the notifier with the 71 /// observer base can be attached to the notifier with the 72 72 /// \e attach() member and can be detached with detach() function. The 73 73 /// alteration handlers should not call any function which signals … … 80 80 /// be rolled back by calling the \e erase() or \e clear() 81 81 /// functions. Thence the \e erase() and \e clear() should not throw 82 /// exception. Actullay, it can be throw only 82 /// exception. Actullay, it can be throw only 83 83 /// \ref AlterationObserver::ImmediateDetach ImmediateDetach 84 84 /// exception which detach the observer from the notifier. … … 86 86 /// There are some place when the alteration observing is not completly 87 87 /// reliable. If we want to carry out the node degree in the graph 88 /// as in the \ref InDegMap and we use the reverseEdge that cause 88 /// as in the \ref InDegMap and we use the reverseEdge that cause 89 89 /// unreliable functionality. Because the alteration observing signals 90 90 /// only erasing and adding but not the reversing it will stores bad … … 105 105 typedef _Item Item; 106 106 107 /// \brief Exception which can be called from \e clear() and 107 /// \brief Exception which can be called from \e clear() and 108 108 /// \e erase(). 109 109 /// … … 128 128 /// The build() and clear() members are to notify the observer 129 129 /// about the container is built from an empty container or 130 /// is cleared to an empty container. 130 /// is cleared to an empty container. 131 131 132 132 class ObserverBase { … … 139 139 /// 140 140 /// Default constructor for ObserverBase. 141 /// 141 /// 142 142 ObserverBase() : _notifier(0) {} 143 143 … … 152 152 /// 153 153 /// Constructor which attach the obserever to the same notifier as 154 /// the other observer is attached to. 154 /// the other observer is attached to. 155 155 ObserverBase(const ObserverBase& copy) { 156 156 if (copy.attached()) { 157 157 attach(*copy.notifier()); 158 159 } 160 158 } 159 } 160 161 161 /// \brief Destructor 162 162 virtual ~ObserverBase() { … … 171 171 /// 172 172 void attach(AlterationNotifier& nf) { 173 174 } 175 173 nf.attach(*this); 174 } 175 176 176 /// \brief Detaches the observer into an AlterationNotifier. 177 177 /// … … 181 181 _notifier->detach(*this); 182 182 } 183 184 /// \brief Gives back a pointer to the notifier which the map 183 184 /// \brief Gives back a pointer to the notifier which the map 185 185 /// attached into. 186 186 /// … … 189 189 /// 190 190 Notifier* notifier() const { return const_cast<Notifier*>(_notifier); } 191 191 192 192 /// Gives back true when the observer is attached into a notifier. 193 193 bool attached() const { return _notifier != 0; } … … 198 198 199 199 protected: 200 200 201 201 Notifier* _notifier; 202 202 typename std::list<ObserverBase*>::iterator _index; … … 210 210 virtual void add(const Item&) = 0; 211 211 212 /// \brief The member function to notificate the observer about 212 /// \brief The member function to notificate the observer about 213 213 /// more item is added to the container. 214 214 /// … … 223 223 /// The erase() member function notificates the observer about an 224 224 /// item is erased from the container. It have to be overrided in 225 /// the subclasses. 225 /// the subclasses. 226 226 virtual void erase(const Item&) = 0; 227 227 228 /// \brief The member function to notificate the observer about 228 /// \brief The member function to notificate the observer about 229 229 /// more item is erased from the container. 230 230 /// … … 248 248 /// The clear() member function notificates the observer about all 249 249 /// items are erased from the container. It have to be overrided in 250 /// the subclasses. 250 /// the subclasses. 251 251 virtual void clear() = 0; 252 252 253 253 }; 254 254 255 255 protected: 256 256 257 257 const Container* container; 258 258 259 typedef std::list<ObserverBase*> Observers; 259 typedef std::list<ObserverBase*> Observers; 260 260 Observers _observers; 261 261 262 262 263 263 public: 264 264 265 265 /// \brief Default constructor. 266 266 /// 267 /// The default constructor of the AlterationNotifier. 267 /// The default constructor of the AlterationNotifier. 268 268 /// It creates an empty notifier. 269 AlterationNotifier() 269 AlterationNotifier() 270 270 : container(0) {} 271 271 … … 273 273 /// 274 274 /// Constructor with the observed container parameter. 275 AlterationNotifier(const Container& _container) 275 AlterationNotifier(const Container& _container) 276 276 : container(&_container) {} 277 277 278 /// \brief Copy Constructor of the AlterationNotifier. 279 /// 280 /// Copy constructor of the AlterationNotifier. 278 /// \brief Copy Constructor of the AlterationNotifier. 279 /// 280 /// Copy constructor of the AlterationNotifier. 281 281 /// It creates only an empty notifier because the copiable 282 282 /// notifier's observers have to be registered still into that notifier. 283 AlterationNotifier(const AlterationNotifier& _notifier) 283 AlterationNotifier(const AlterationNotifier& _notifier) 284 284 : container(_notifier.container) {} 285 285 286 286 /// \brief Destructor. 287 /// 287 /// 288 288 /// Destructor of the AlterationNotifier. 289 289 /// … … 291 291 typename Observers::iterator it; 292 292 for (it = _observers.begin(); it != _observers.end(); ++it) { 293 293 (*it)->_notifier = 0; 294 294 } 295 295 } … … 339 339 return container->maxId(Item()); 340 340 } 341 341 342 342 protected: 343 343 … … 345 345 observer._index = _observers.insert(_observers.begin(), &observer); 346 346 observer._notifier = this; 347 } 347 } 348 348 349 349 void detach(ObserverBase& observer) { … … 354 354 355 355 public: 356 357 /// \brief Notifies all the registed observers about an item added to 358 /// the container. 359 /// 360 /// It notifies all the registed observers about an item added to 361 /// the container. 362 /// 356 357 /// \brief Notifies all the registed observers about an item added to 358 /// the container. 359 /// 360 /// It notifies all the registed observers about an item added to 361 /// the container. 362 /// 363 363 void add(const Item& item) { 364 364 typename Observers::reverse_iterator it; … … 374 374 throw; 375 375 } 376 } 377 378 /// \brief Notifies all the registed observers about more item added to 379 /// the container. 380 /// 381 /// It notifies all the registed observers about more item added to 382 /// the container. 383 /// 376 } 377 378 /// \brief Notifies all the registed observers about more item added to 379 /// the container. 380 /// 381 /// It notifies all the registed observers about more item added to 382 /// the container. 383 /// 384 384 void add(const std::vector<Item>& items) { 385 385 typename Observers::reverse_iterator it; … … 395 395 throw; 396 396 } 397 } 398 399 /// \brief Notifies all the registed observers about an item erased from 400 /// the container. 401 /// 402 /// It notifies all the registed observers about an item erased from 403 /// the container. 404 /// 397 } 398 399 /// \brief Notifies all the registed observers about an item erased from 400 /// the container. 401 /// 402 /// It notifies all the registed observers about an item erased from 403 /// the container. 404 /// 405 405 void erase(const Item& item) throw() { 406 406 typename Observers::iterator it = _observers.begin(); … … 417 417 } 418 418 419 /// \brief Notifies all the registed observers about more item erased 419 /// \brief Notifies all the registed observers about more item erased 420 420 /// from the container. 421 /// 422 /// It notifies all the registed observers about more item erased from 423 /// the container. 424 /// 421 /// 422 /// It notifies all the registed observers about more item erased from 423 /// the container. 424 /// 425 425 void erase(const std::vector<Item>& items) { 426 426 typename Observers::iterator it = _observers.begin(); … … 437 437 } 438 438 439 /// \brief Notifies all the registed observers about the container is 439 /// \brief Notifies all the registed observers about the container is 440 440 /// built. 441 /// 441 /// 442 442 /// Notifies all the registed observers about the container is built 443 443 /// from an empty container. … … 457 457 } 458 458 459 /// \brief Notifies all the registed observers about all items are 459 /// \brief Notifies all the registed observers about all items are 460 460 /// erased. 461 461 /// -
lemon/bits/array_map.h
r107 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 39 39 /// The ArrayMap template class is graph map structure what 40 40 /// automatically updates the map when a key is added to or erased from 41 /// the map. This map uses the allocators to implement 41 /// the map. This map uses the allocators to implement 42 42 /// the container functionality. 43 43 /// … … 45 45 /// the Value type of the map. 46 46 template <typename _Graph, typename _Item, typename _Value> 47 class ArrayMap 47 class ArrayMap 48 48 : public ItemSetTraits<_Graph, _Item>::ItemNotifier::ObserverBase { 49 49 public: 50 /// The graph type of the maps. 50 /// The graph type of the maps. 51 51 typedef _Graph Graph; 52 52 /// The item type of the map. … … 70 70 /// The MapBase of the Map which imlements the core regisitry function. 71 71 typedef typename Notifier::ObserverBase Parent; 72 72 73 73 private: 74 74 typedef std::allocator<Value> Allocator; … … 85 85 Item it; 86 86 for (nf->first(it); it != INVALID; nf->next(it)) { 87 88 89 } 90 } 91 92 /// \brief Constructor to use default value to initialize the map. 93 /// 94 /// It constructs a map and initialize all of the the map. 87 int id = nf->id(it);; 88 allocator.construct(&(values[id]), Value()); 89 } 90 } 91 92 /// \brief Constructor to use default value to initialize the map. 93 /// 94 /// It constructs a map and initialize all of the the map. 95 95 ArrayMap(const Graph& graph, const Value& value) { 96 96 Parent::attach(graph.notifier(Item())); … … 99 99 Item it; 100 100 for (nf->first(it); it != INVALID; nf->next(it)) { 101 102 103 } 101 int id = nf->id(it);; 102 allocator.construct(&(values[id]), value); 103 } 104 104 } 105 105 106 106 /// \brief Constructor to copy a map of the same map type. 107 107 /// 108 /// Constructor to copy a map of the same map type. 108 /// Constructor to copy a map of the same map type. 109 109 ArrayMap(const ArrayMap& copy) : Parent() { 110 110 if (copy.attached()) { 111 111 attach(*copy.notifier()); 112 112 } 113 113 capacity = copy.capacity; … … 117 117 Item it; 118 118 for (nf->first(it); it != INVALID; nf->next(it)) { 119 120 119 int id = nf->id(it);; 120 allocator.construct(&(values[id]), copy.values[id]); 121 121 } 122 122 } … … 125 125 /// 126 126 /// This operator assigns for each item in the map the 127 /// value mapped to the same item in the copied map. 127 /// value mapped to the same item in the copied map. 128 128 /// The parameter map should be indiced with the same 129 129 /// itemset because this assign operator does not change 130 /// the container of the map. 130 /// the container of the map. 131 131 ArrayMap& operator=(const ArrayMap& cmap) { 132 132 return operator=<ArrayMap>(cmap); … … 139 139 /// concecpt and could be indiced by the current item set of 140 140 /// the NodeMap. In this case the value for each item 141 /// is assigned by the value of the given ReadMap. 141 /// is assigned by the value of the given ReadMap. 142 142 template <typename CMap> 143 143 ArrayMap& operator=(const CMap& cmap) { … … 152 152 153 153 /// \brief The destructor of the map. 154 /// 154 /// 155 155 /// The destructor of the map. 156 virtual ~ArrayMap() { 156 virtual ~ArrayMap() { 157 157 if (attached()) { 158 159 160 } 161 } 162 158 clear(); 159 detach(); 160 } 161 } 162 163 163 protected: 164 164 … … 169 169 public: 170 170 171 /// \brief The subscript operator. 171 /// \brief The subscript operator. 172 172 /// 173 173 /// The subscript operator. The map can be subscripted by the 174 /// actual keys of the graph. 174 /// actual keys of the graph. 175 175 Value& operator[](const Key& key) { 176 176 int id = Parent::notifier()->id(key); 177 177 return values[id]; 178 } 179 178 } 179 180 180 /// \brief The const subscript operator. 181 181 /// 182 182 /// The const subscript operator. The map can be subscripted by the 183 /// actual keys of the graph. 183 /// actual keys of the graph. 184 184 const Value& operator[](const Key& key) const { 185 185 int id = Parent::notifier()->id(key); … … 188 188 189 189 /// \brief Setter function of the map. 190 /// 190 /// 191 191 /// Setter function of the map. Equivalent with map[key] = val. 192 192 /// This is a compatibility feature with the not dereferable maps. … … 198 198 199 199 /// \brief Adds a new key to the map. 200 /// 200 /// 201 201 /// It adds a new key to the map. It called by the observer notifier 202 /// and it overrides the add() member function of the observer base. 202 /// and it overrides the add() member function of the observer base. 203 203 virtual void add(const Key& key) { 204 204 Notifier* nf = Parent::notifier(); 205 205 int id = nf->id(key); 206 206 if (id >= capacity) { 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 207 int new_capacity = (capacity == 0 ? 1 : capacity); 208 while (new_capacity <= id) { 209 new_capacity <<= 1; 210 } 211 Value* new_values = allocator.allocate(new_capacity); 212 Item it; 213 for (nf->first(it); it != INVALID; nf->next(it)) { 214 int jd = nf->id(it);; 215 if (id != jd) { 216 allocator.construct(&(new_values[jd]), values[jd]); 217 allocator.destroy(&(values[jd])); 218 } 219 } 220 if (capacity != 0) allocator.deallocate(values, capacity); 221 values = new_values; 222 capacity = new_capacity; 223 223 } 224 224 allocator.construct(&(values[id]), Value()); … … 226 226 227 227 /// \brief Adds more new keys to the map. 228 /// 228 /// 229 229 /// It adds more new keys to the map. It called by the observer notifier 230 /// and it overrides the add() member function of the observer base. 230 /// and it overrides the add() member function of the observer base. 231 231 virtual void add(const std::vector<Key>& keys) { 232 232 Notifier* nf = Parent::notifier(); 233 233 int max_id = -1; 234 234 for (int i = 0; i < int(keys.size()); ++i) { 235 236 237 238 235 int id = nf->id(keys[i]); 236 if (id > max_id) { 237 max_id = id; 238 } 239 239 } 240 240 if (max_id >= capacity) { 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 241 int new_capacity = (capacity == 0 ? 1 : capacity); 242 while (new_capacity <= max_id) { 243 new_capacity <<= 1; 244 } 245 Value* new_values = allocator.allocate(new_capacity); 246 Item it; 247 for (nf->first(it); it != INVALID; nf->next(it)) { 248 int id = nf->id(it); 249 bool found = false; 250 for (int i = 0; i < int(keys.size()); ++i) { 251 int jd = nf->id(keys[i]); 252 if (id == jd) { 253 found = true; 254 break; 255 } 256 } 257 if (found) continue; 258 allocator.construct(&(new_values[id]), values[id]); 259 allocator.destroy(&(values[id])); 260 } 261 if (capacity != 0) allocator.deallocate(values, capacity); 262 values = new_values; 263 capacity = new_capacity; 264 264 } 265 265 for (int i = 0; i < int(keys.size()); ++i) { 266 267 268 } 269 } 270 266 int id = nf->id(keys[i]); 267 allocator.construct(&(values[id]), Value()); 268 } 269 } 270 271 271 /// \brief Erase a key from the map. 272 272 /// 273 273 /// Erase a key from the map. It called by the observer notifier 274 /// and it overrides the erase() member function of the observer base. 274 /// and it overrides the erase() member function of the observer base. 275 275 virtual void erase(const Key& key) { 276 276 int id = Parent::notifier()->id(key); … … 281 281 /// 282 282 /// Erase more keys from the map. It called by the observer notifier 283 /// and it overrides the erase() member function of the observer base. 283 /// and it overrides the erase() member function of the observer base. 284 284 virtual void erase(const std::vector<Key>& keys) { 285 285 for (int i = 0; i < int(keys.size()); ++i) { 286 287 286 int id = Parent::notifier()->id(keys[i]); 287 allocator.destroy(&(values[id])); 288 288 } 289 289 } 290 290 291 291 /// \brief Buildes the map. 292 /// 292 /// 293 293 /// It buildes the map. It called by the observer notifier 294 /// and it overrides the build() member function of the observer base. 294 /// and it overrides the build() member function of the observer base. 295 295 virtual void build() { 296 296 Notifier* nf = Parent::notifier(); … … 298 298 Item it; 299 299 for (nf->first(it); it != INVALID; nf->next(it)) { 300 301 302 } 300 int id = nf->id(it);; 301 allocator.construct(&(values[id]), Value()); 302 } 303 303 } 304 304 … … 306 306 /// 307 307 /// It erase all items from the map. It called by the observer notifier 308 /// and it overrides the clear() member function of the observer base. 309 virtual void clear() { 308 /// and it overrides the clear() member function of the observer base. 309 virtual void clear() { 310 310 Notifier* nf = Parent::notifier(); 311 311 if (capacity != 0) { 312 313 314 315 316 } 317 318 312 Item it; 313 for (nf->first(it); it != INVALID; nf->next(it)) { 314 int id = nf->id(it); 315 allocator.destroy(&(values[id])); 316 } 317 allocator.deallocate(values, capacity); 318 capacity = 0; 319 319 } 320 320 } 321 321 322 322 private: 323 323 324 324 void allocate_memory() { 325 325 int max_id = Parent::notifier()->maxId(); 326 326 if (max_id == -1) { 327 328 329 327 capacity = 0; 328 values = 0; 329 return; 330 330 } 331 331 capacity = 1; 332 332 while (capacity <= max_id) { 333 334 } 335 values = allocator.allocate(capacity); 336 } 333 capacity <<= 1; 334 } 335 values = allocator.allocate(capacity); 336 } 337 337 338 338 int capacity; … … 340 340 Allocator allocator; 341 341 342 }; 342 }; 343 343 344 344 } 345 345 346 #endif 346 #endif -
lemon/bits/base_extender.h
r107 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 64 64 65 65 bool operator==(const Arc &that) const { 66 66 return forward==that.forward && Edge(*this)==Edge(that); 67 67 } 68 68 bool operator!=(const Arc &that) const { 69 69 return forward!=that.forward || Edge(*this)!=Edge(that); 70 70 } 71 71 bool operator<(const Arc &that) const { 72 73 72 return forward<that.forward || 73 (!(that.forward<forward) && Edge(*this)<Edge(that)); 74 74 } 75 75 }; … … 118 118 void next(Arc &e) const { 119 119 if( e.forward ) { 120 120 e.forward = false; 121 121 } 122 122 else { 123 124 123 Parent::next(e); 124 e.forward = true; 125 125 } 126 126 } … … 129 129 Parent::firstIn(e,n); 130 130 if( Edge(e) != INVALID ) { 131 131 e.forward = false; 132 132 } 133 133 else { 134 135 134 Parent::firstOut(e,n); 135 e.forward = true; 136 136 } 137 137 } 138 138 void nextOut(Arc &e) const { 139 139 if( ! e.forward ) { 140 141 142 143 144 145 140 Node n = Parent::target(e); 141 Parent::nextIn(e); 142 if( Edge(e) == INVALID ) { 143 Parent::firstOut(e, n); 144 e.forward = true; 145 } 146 146 } 147 147 else { 148 148 Parent::nextOut(e); 149 149 } 150 150 } … … 153 153 Parent::firstOut(e,n); 154 154 if( Edge(e) != INVALID ) { 155 155 e.forward = false; 156 156 } 157 157 else { 158 159 158 Parent::firstIn(e,n); 159 e.forward = true; 160 160 } 161 161 } 162 162 void nextIn(Arc &e) const { 163 163 if( ! e.forward ) { 164 165 166 167 168 169 164 Node n = Parent::source(e); 165 Parent::nextOut(e); 166 if( Edge(e) == INVALID ) { 167 Parent::firstIn(e, n); 168 e.forward = true; 169 } 170 170 } 171 171 else { 172 172 Parent::nextIn(e); 173 173 } 174 174 } … … 184 184 void nextInc(Edge &e, bool &d) const { 185 185 if (d) { 186 187 188 189 190 191 } else { 192 186 Node s = Parent::source(e); 187 Parent::nextOut(e); 188 if (e != INVALID) return; 189 d = false; 190 Parent::firstIn(e, s); 191 } else { 192 Parent::nextIn(e); 193 193 } 194 194 } … … 241 241 Arc findArc(Node s, Node t, Arc p = INVALID) const { 242 242 if (p == INVALID) { 243 244 245 246 243 Edge arc = Parent::findArc(s, t); 244 if (arc != INVALID) return direct(arc, true); 245 arc = Parent::findArc(t, s); 246 if (arc != INVALID) return direct(arc, false); 247 247 } else if (direction(p)) { 248 249 250 251 if (arc != INVALID) return direct(arc, false); 252 } else { 253 254 if (arc != INVALID) return direct(arc, false); 248 Edge arc = Parent::findArc(s, t, p); 249 if (arc != INVALID) return direct(arc, true); 250 arc = Parent::findArc(t, s); 251 if (arc != INVALID) return direct(arc, false); 252 } else { 253 Edge arc = Parent::findArc(t, s, p); 254 if (arc != INVALID) return direct(arc, false); 255 255 } 256 256 return INVALID; … … 268 268 if (arc != INVALID) return arc; 269 269 arc = Parent::findArc(t, s); 270 if (arc != INVALID) return arc; 270 if (arc != INVALID) return arc; 271 271 } else { 272 272 Edge arc = Parent::findArc(t, s, p); 273 if (arc != INVALID) return arc; 273 if (arc != INVALID) return arc; 274 274 } 275 275 } else { … … 300 300 Red() {} 301 301 Red(const Node& node) : Node(node) { 302 LEMON_ASSERT(Parent::red(node) || node == INVALID, 303 302 LEMON_ASSERT(Parent::red(node) || node == INVALID, 303 typename Parent::NodeSetError()); 304 304 } 305 305 Red& operator=(const Node& node) { 306 LEMON_ASSERT(Parent::red(node) || node == INVALID, 307 306 LEMON_ASSERT(Parent::red(node) || node == INVALID, 307 typename Parent::NodeSetError()); 308 308 Node::operator=(node); 309 309 return *this; … … 332 332 Blue() {} 333 333 Blue(const Node& node) : Node(node) { 334 335 334 LEMON_ASSERT(Parent::blue(node) || node == INVALID, 335 typename Parent::NodeSetError()); 336 336 } 337 337 Blue& operator=(const Node& node) { 338 LEMON_ASSERT(Parent::blue(node) || node == INVALID, 339 338 LEMON_ASSERT(Parent::blue(node) || node == INVALID, 339 typename Parent::NodeSetError()); 340 340 Node::operator=(node); 341 341 return *this; … … 354 354 Parent::nextBlue(static_cast<Node&>(node)); 355 355 } 356 356 357 357 int id(const Blue& node) const { 358 358 return Parent::redId(node); … … 368 368 void firstInc(Edge& arc, bool& dir, const Node& node) const { 369 369 if (Parent::red(node)) { 370 371 372 } else { 373 374 370 Parent::firstFromRed(arc, node); 371 dir = true; 372 } else { 373 Parent::firstFromBlue(arc, node); 374 dir = static_cast<Edge&>(arc) == INVALID; 375 375 } 376 376 } 377 377 void nextInc(Edge& arc, bool& dir) const { 378 378 if (dir) { 379 380 } else { 381 382 379 Parent::nextFromRed(arc); 380 } else { 381 Parent::nextFromBlue(arc); 382 if (arc == INVALID) dir = true; 383 383 } 384 384 } … … 390 390 391 391 Arc(const Edge& arc, bool _forward) 392 392 : Edge(arc), forward(_forward) {} 393 393 394 394 public: … … 396 396 Arc (Invalid) : Edge(INVALID), forward(true) {} 397 397 bool operator==(const Arc& i) const { 398 398 return Edge::operator==(i) && forward == i.forward; 399 399 } 400 400 bool operator!=(const Arc& i) const { 401 401 return Edge::operator!=(i) || forward != i.forward; 402 402 } 403 403 bool operator<(const Arc& i) const { 404 return Edge::operator<(i) || 405 404 return Edge::operator<(i) || 405 (!(i.forward<forward) && Edge(*this)<Edge(i)); 406 406 } 407 407 }; … … 414 414 void next(Arc& arc) const { 415 415 if (!arc.forward) { 416 416 Parent::next(static_cast<Edge&>(arc)); 417 417 } 418 418 arc.forward = !arc.forward; … … 421 421 void firstOut(Arc& arc, const Node& node) const { 422 422 if (Parent::red(node)) { 423 424 425 } else { 426 427 423 Parent::firstFromRed(arc, node); 424 arc.forward = true; 425 } else { 426 Parent::firstFromBlue(arc, node); 427 arc.forward = static_cast<Edge&>(arc) == INVALID; 428 428 } 429 429 } 430 430 void nextOut(Arc& arc) const { 431 431 if (arc.forward) { 432 433 } else { 434 432 Parent::nextFromRed(arc); 433 } else { 434 Parent::nextFromBlue(arc); 435 435 arc.forward = static_cast<Edge&>(arc) == INVALID; 436 436 } … … 439 439 void firstIn(Arc& arc, const Node& node) const { 440 440 if (Parent::blue(node)) { 441 442 arc.forward = true; 443 } else { 444 445 441 Parent::firstFromBlue(arc, node); 442 arc.forward = true; 443 } else { 444 Parent::firstFromRed(arc, node); 445 arc.forward = static_cast<Edge&>(arc) == INVALID; 446 446 } 447 447 } 448 448 void nextIn(Arc& arc) const { 449 449 if (arc.forward) { 450 451 } else { 452 453 450 Parent::nextFromBlue(arc); 451 } else { 452 Parent::nextFromRed(arc); 453 arc.forward = static_cast<Edge&>(arc) == INVALID; 454 454 } 455 455 } … … 463 463 464 464 int id(const Arc& arc) const { 465 return (Parent::id(static_cast<const Edge&>(arc)) << 1) + 465 return (Parent::id(static_cast<const Edge&>(arc)) << 1) + 466 466 (arc.forward ? 0 : 1); 467 467 } -
lemon/bits/bezier.h
r184 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 45 45 Bezier1() {} 46 46 Bezier1(Point _p1, Point _p2) :p1(_p1), p2(_p2) {} 47 47 48 48 Point operator()(double t) const 49 49 { … … 55 55 return Bezier1(p1,conv(p1,p2,t)); 56 56 } 57 57 58 58 Bezier1 after(double t) const 59 59 { … … 88 88 return Bezier2(p1,q,conv(q,r,t)); 89 89 } 90 90 91 91 Bezier2 after(double t) const 92 92 { … … 111 111 Bezier3(Point _p1, Point _p2, Point _p3, Point _p4) 112 112 : p1(_p1), p2(_p2), p3(_p3), p4(_p4) {} 113 Bezier3(const Bezier1 &b) : p1(b.p1), p2(conv(b.p1,b.p2,1.0/3.0)), 114 113 Bezier3(const Bezier1 &b) : p1(b.p1), p2(conv(b.p1,b.p2,1.0/3.0)), 114 p3(conv(b.p1,b.p2,2.0/3.0)), p4(b.p2) {} 115 115 Bezier3(const Bezier2 &b) : p1(b.p1), p2(conv(b.p1,b.p2,2.0/3.0)), 116 117 118 Point operator()(double t) const 116 p3(conv(b.p2,b.p3,1.0/3.0)), p4(b.p3) {} 117 118 Point operator()(double t) const 119 119 { 120 120 // return Bezier2(conv(p1,p2,t),conv(p2,p3,t),conv(p3,p4,t))(t); 121 121 return ((1-t)*(1-t)*(1-t))*p1+(3*t*(1-t)*(1-t))*p2+ 122 122 (3*t*t*(1-t))*p3+(t*t*t)*p4; 123 123 } 124 124 Bezier3 before(double t) const … … 132 132 return Bezier3(p1,p,a,c); 133 133 } 134 134 135 135 Bezier3 after(double t) const 136 136 { … … 147 147 Bezier2 grad() const { return Bezier2(3.0*(p2-p1),3.0*(p3-p2),3.0*(p4-p3)); } 148 148 Bezier2 norm() const { return Bezier2(3.0*rot90(p2-p1), 149 150 149 3.0*rot90(p3-p2), 150 3.0*rot90(p4-p3)); } 151 151 Point grad(double t) const { return grad()(t); } 152 152 Point norm(double t) const { return rot90(grad(t)); } 153 153 154 154 template<class R,class F,class S,class D> 155 R recSplit(F &_f,const S &_s,D _d) const 155 R recSplit(F &_f,const S &_s,D _d) const 156 156 { 157 157 const Point a=(p1+p2)/2; … … 165 165 return _s(f1,f2); 166 166 } 167 167 168 168 }; 169 169 -
lemon/bits/default_map.h
r107 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 30 30 31 31 namespace lemon { 32 33 32 33 34 34 //#ifndef LEMON_USE_DEBUG_MAP 35 35 … … 141 141 }; 142 142 143 // #else 143 // #else 144 144 145 145 // template <typename _Graph, typename _Item, typename _Value> … … 148 148 // }; 149 149 150 // #endif 150 // #endif 151 151 152 152 /// \e 153 153 template <typename _Graph, typename _Item, typename _Value> 154 class DefaultMap 154 class DefaultMap 155 155 : public DefaultMapSelector<_Graph, _Item, _Value>::Map { 156 156 public: 157 157 typedef typename DefaultMapSelector<_Graph, _Item, _Value>::Map Parent; 158 158 typedef DefaultMap<_Graph, _Item, _Value> Map; 159 159 160 160 typedef typename Parent::Graph Graph; 161 161 typedef typename Parent::Value Value; 162 162 163 163 explicit DefaultMap(const Graph& graph) : Parent(graph) {} 164 DefaultMap(const Graph& graph, const Value& value) 164 DefaultMap(const Graph& graph, const Value& value) 165 165 : Parent(graph, value) {} 166 166 -
lemon/bits/graph_extender.h
r125 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 67 67 Node oppositeNode(const Node &node, const Arc &arc) const { 68 68 if (node == Parent::source(arc)) 69 69 return Parent::target(arc); 70 70 else if(node == Parent::target(arc)) 71 71 return Parent::source(arc); 72 72 else 73 73 return INVALID; 74 74 } 75 75 … … 90 90 return node_notifier; 91 91 } 92 92 93 93 ArcNotifier& notifier(Arc) const { 94 94 return arc_notifier; 95 95 } 96 96 97 class NodeIt : public Node { 97 class NodeIt : public Node { 98 98 const Digraph* _digraph; 99 99 public: … … 104 104 105 105 explicit NodeIt(const Digraph& digraph) : _digraph(&digraph) { 106 107 } 108 109 NodeIt(const Digraph& digraph, const Node& node) 110 111 112 NodeIt& operator++() { 113 114 return *this; 115 } 116 117 }; 118 119 120 class ArcIt : public Arc { 106 _digraph->first(static_cast<Node&>(*this)); 107 } 108 109 NodeIt(const Digraph& digraph, const Node& node) 110 : Node(node), _digraph(&digraph) {} 111 112 NodeIt& operator++() { 113 _digraph->next(*this); 114 return *this; 115 } 116 117 }; 118 119 120 class ArcIt : public Arc { 121 121 const Digraph* _digraph; 122 122 public: … … 127 127 128 128 explicit ArcIt(const Digraph& digraph) : _digraph(&digraph) { 129 130 } 131 132 ArcIt(const Digraph& digraph, const Arc& arc) : 133 134 135 ArcIt& operator++() { 136 137 return *this; 138 } 139 140 }; 141 142 143 class OutArcIt : public Arc { 129 _digraph->first(static_cast<Arc&>(*this)); 130 } 131 132 ArcIt(const Digraph& digraph, const Arc& arc) : 133 Arc(arc), _digraph(&digraph) { } 134 135 ArcIt& operator++() { 136 _digraph->next(*this); 137 return *this; 138 } 139 140 }; 141 142 143 class OutArcIt : public Arc { 144 144 const Digraph* _digraph; 145 145 public: … … 149 149 OutArcIt(Invalid i) : Arc(i) { } 150 150 151 OutArcIt(const Digraph& digraph, const Node& node) 152 153 154 } 155 156 OutArcIt(const Digraph& digraph, const Arc& arc) 157 158 159 OutArcIt& operator++() { 160 161 return *this; 162 } 163 164 }; 165 166 167 class InArcIt : public Arc { 151 OutArcIt(const Digraph& digraph, const Node& node) 152 : _digraph(&digraph) { 153 _digraph->firstOut(*this, node); 154 } 155 156 OutArcIt(const Digraph& digraph, const Arc& arc) 157 : Arc(arc), _digraph(&digraph) {} 158 159 OutArcIt& operator++() { 160 _digraph->nextOut(*this); 161 return *this; 162 } 163 164 }; 165 166 167 class InArcIt : public Arc { 168 168 const Digraph* _digraph; 169 169 public: … … 173 173 InArcIt(Invalid i) : Arc(i) { } 174 174 175 InArcIt(const Digraph& digraph, const Node& node) 176 177 178 } 179 180 InArcIt(const Digraph& digraph, const Arc& arc) : 181 182 183 InArcIt& operator++() { 184 185 return *this; 175 InArcIt(const Digraph& digraph, const Node& node) 176 : _digraph(&digraph) { 177 _digraph->firstIn(*this, node); 178 } 179 180 InArcIt(const Digraph& digraph, const Arc& arc) : 181 Arc(arc), _digraph(&digraph) {} 182 183 InArcIt& operator++() { 184 _digraph->nextIn(*this); 185 return *this; 186 186 } 187 187 … … 216 216 } 217 217 218 218 219 219 template <typename _Value> 220 class NodeMap 220 class NodeMap 221 221 : public MapExtender<DefaultMap<Digraph, Node, _Value> > { 222 222 public: … … 224 224 typedef MapExtender<DefaultMap<Digraph, Node, _Value> > Parent; 225 225 226 explicit NodeMap(const Digraph& digraph) 227 228 NodeMap(const Digraph& digraph, const _Value& value) 229 226 explicit NodeMap(const Digraph& digraph) 227 : Parent(digraph) {} 228 NodeMap(const Digraph& digraph, const _Value& value) 229 : Parent(digraph, value) {} 230 230 231 231 NodeMap& operator=(const NodeMap& cmap) { 232 232 return operator=<NodeMap>(cmap); 233 233 } 234 234 … … 236 236 NodeMap& operator=(const CMap& cmap) { 237 237 Parent::operator=(cmap); 238 238 return *this; 239 239 } 240 240 … … 242 242 243 243 template <typename _Value> 244 class ArcMap 244 class ArcMap 245 245 : public MapExtender<DefaultMap<Digraph, Arc, _Value> > { 246 246 public: … … 248 248 typedef MapExtender<DefaultMap<Digraph, Arc, _Value> > Parent; 249 249 250 explicit ArcMap(const Digraph& digraph) 251 252 ArcMap(const Digraph& digraph, const _Value& value) 253 250 explicit ArcMap(const Digraph& digraph) 251 : Parent(digraph) {} 252 ArcMap(const Digraph& digraph, const _Value& value) 253 : Parent(digraph, value) {} 254 254 255 255 ArcMap& operator=(const ArcMap& cmap) { 256 256 return operator=<ArcMap>(cmap); 257 257 } 258 258 … … 260 260 ArcMap& operator=(const CMap& cmap) { 261 261 Parent::operator=(cmap); 262 262 return *this; 263 263 } 264 264 }; … … 270 270 return node; 271 271 } 272 272 273 273 Arc addArc(const Node& from, const Node& to) { 274 274 Arc arc = Parent::addArc(from, to); … … 294 294 Parent::firstOut(arc, node); 295 295 while (arc != INVALID ) { 296 297 298 } 296 erase(arc); 297 Parent::firstOut(arc, node); 298 } 299 299 300 300 Parent::firstIn(arc, node); 301 301 while (arc != INVALID ) { 302 303 302 erase(arc); 303 Parent::firstIn(arc, node); 304 304 } 305 305 … … 307 307 Parent::erase(node); 308 308 } 309 309 310 310 void erase(const Arc& arc) { 311 311 notifier(Arc()).erase(arc); … … 316 316 node_notifier.setContainer(*this); 317 317 arc_notifier.setContainer(*this); 318 } 319 318 } 319 320 320 321 321 ~DigraphExtender() { … … 328 328 /// 329 329 /// \brief Extender for the Graphs 330 template <typename Base> 330 template <typename Base> 331 331 class GraphExtender : public Base { 332 332 public: 333 333 334 334 typedef Base Parent; 335 335 typedef GraphExtender Graph; … … 341 341 typedef typename Parent::Edge Edge; 342 342 343 // Graph extension 343 // Graph extension 344 344 345 345 int maxId(Node) const { … … 369 369 Node oppositeNode(const Node &n, const Edge &e) const { 370 370 if( n == Parent::u(e)) 371 371 return Parent::v(e); 372 372 else if( n == Parent::v(e)) 373 373 return Parent::u(e); 374 374 else 375 375 return INVALID; 376 376 } 377 377 … … 403 403 return node_notifier; 404 404 } 405 405 406 406 ArcNotifier& notifier(Arc) const { 407 407 return arc_notifier; … … 414 414 415 415 416 class NodeIt : public Node { 416 class NodeIt : public Node { 417 417 const Graph* _graph; 418 418 public: … … 423 423 424 424 explicit NodeIt(const Graph& graph) : _graph(&graph) { 425 426 } 427 428 NodeIt(const Graph& graph, const Node& node) 429 430 431 NodeIt& operator++() { 432 433 return *this; 434 } 435 436 }; 437 438 439 class ArcIt : public Arc { 425 _graph->first(static_cast<Node&>(*this)); 426 } 427 428 NodeIt(const Graph& graph, const Node& node) 429 : Node(node), _graph(&graph) {} 430 431 NodeIt& operator++() { 432 _graph->next(*this); 433 return *this; 434 } 435 436 }; 437 438 439 class ArcIt : public Arc { 440 440 const Graph* _graph; 441 441 public: … … 446 446 447 447 explicit ArcIt(const Graph& graph) : _graph(&graph) { 448 449 } 450 451 ArcIt(const Graph& graph, const Arc& arc) : 452 453 454 ArcIt& operator++() { 455 456 return *this; 457 } 458 459 }; 460 461 462 class OutArcIt : public Arc { 448 _graph->first(static_cast<Arc&>(*this)); 449 } 450 451 ArcIt(const Graph& graph, const Arc& arc) : 452 Arc(arc), _graph(&graph) { } 453 454 ArcIt& operator++() { 455 _graph->next(*this); 456 return *this; 457 } 458 459 }; 460 461 462 class OutArcIt : public Arc { 463 463 const Graph* _graph; 464 464 public: … … 468 468 OutArcIt(Invalid i) : Arc(i) { } 469 469 470 OutArcIt(const Graph& graph, const Node& node) 471 472 473 } 474 475 OutArcIt(const Graph& graph, const Arc& arc) 476 477 478 OutArcIt& operator++() { 479 480 return *this; 481 } 482 483 }; 484 485 486 class InArcIt : public Arc { 470 OutArcIt(const Graph& graph, const Node& node) 471 : _graph(&graph) { 472 _graph->firstOut(*this, node); 473 } 474 475 OutArcIt(const Graph& graph, const Arc& arc) 476 : Arc(arc), _graph(&graph) {} 477 478 OutArcIt& operator++() { 479 _graph->nextOut(*this); 480 return *this; 481 } 482 483 }; 484 485 486 class InArcIt : public Arc { 487 487 const Graph* _graph; 488 488 public: … … 492 492 InArcIt(Invalid i) : Arc(i) { } 493 493 494 InArcIt(const Graph& graph, const Node& node) 495 496 497 } 498 499 InArcIt(const Graph& graph, const Arc& arc) : 500 501 502 InArcIt& operator++() { 503 504 return *this; 505 } 506 507 }; 508 509 510 class EdgeIt : public Parent::Edge { 494 InArcIt(const Graph& graph, const Node& node) 495 : _graph(&graph) { 496 _graph->firstIn(*this, node); 497 } 498 499 InArcIt(const Graph& graph, const Arc& arc) : 500 Arc(arc), _graph(&graph) {} 501 502 InArcIt& operator++() { 503 _graph->nextIn(*this); 504 return *this; 505 } 506 507 }; 508 509 510 class EdgeIt : public Parent::Edge { 511 511 const Graph* _graph; 512 512 public: … … 517 517 518 518 explicit EdgeIt(const Graph& graph) : _graph(&graph) { 519 520 } 521 522 EdgeIt(const Graph& graph, const Edge& edge) : 523 524 525 EdgeIt& operator++() { 526 527 return *this; 519 _graph->first(static_cast<Edge&>(*this)); 520 } 521 522 EdgeIt(const Graph& graph, const Edge& edge) : 523 Edge(edge), _graph(&graph) { } 524 525 EdgeIt& operator++() { 526 _graph->next(*this); 527 return *this; 528 528 } 529 529 … … 541 541 542 542 IncEdgeIt(const Graph& graph, const Node &node) : _graph(&graph) { 543 543 _graph->firstInc(*this, _direction, node); 544 544 } 545 545 546 546 IncEdgeIt(const Graph& graph, const Edge &edge, const Node &node) 547 548 547 : _graph(&graph), Edge(edge) { 548 _direction = (_graph->source(edge) == node); 549 549 } 550 550 551 551 IncEdgeIt& operator++() { 552 553 return *this; 552 _graph->nextInc(*this, _direction); 553 return *this; 554 554 } 555 555 }; … … 599 599 600 600 template <typename _Value> 601 class NodeMap 601 class NodeMap 602 602 : public MapExtender<DefaultMap<Graph, Node, _Value> > { 603 603 public: … … 605 605 typedef MapExtender<DefaultMap<Graph, Node, _Value> > Parent; 606 606 607 NodeMap(const Graph& graph) 608 609 NodeMap(const Graph& graph, const _Value& value) 610 607 NodeMap(const Graph& graph) 608 : Parent(graph) {} 609 NodeMap(const Graph& graph, const _Value& value) 610 : Parent(graph, value) {} 611 611 612 612 NodeMap& operator=(const NodeMap& cmap) { 613 613 return operator=<NodeMap>(cmap); 614 614 } 615 615 … … 617 617 NodeMap& operator=(const CMap& cmap) { 618 618 Parent::operator=(cmap); 619 619 return *this; 620 620 } 621 621 … … 623 623 624 624 template <typename _Value> 625 class ArcMap 625 class ArcMap 626 626 : public MapExtender<DefaultMap<Graph, Arc, _Value> > { 627 627 public: … … 629 629 typedef MapExtender<DefaultMap<Graph, Arc, _Value> > Parent; 630 630 631 ArcMap(const Graph& graph) 632 633 ArcMap(const Graph& graph, const _Value& value) 634 631 ArcMap(const Graph& graph) 632 : Parent(graph) {} 633 ArcMap(const Graph& graph, const _Value& value) 634 : Parent(graph, value) {} 635 635 636 636 ArcMap& operator=(const ArcMap& cmap) { 637 637 return operator=<ArcMap>(cmap); 638 638 } 639 639 … … 641 641 ArcMap& operator=(const CMap& cmap) { 642 642 Parent::operator=(cmap); 643 643 return *this; 644 644 } 645 645 }; … … 647 647 648 648 template <typename _Value> 649 class EdgeMap 649 class EdgeMap 650 650 : public MapExtender<DefaultMap<Graph, Edge, _Value> > { 651 651 public: … … 653 653 typedef MapExtender<DefaultMap<Graph, Edge, _Value> > Parent; 654 654 655 EdgeMap(const Graph& graph) 656 657 658 EdgeMap(const Graph& graph, const _Value& value) 659 655 EdgeMap(const Graph& graph) 656 : Parent(graph) {} 657 658 EdgeMap(const Graph& graph, const _Value& value) 659 : Parent(graph, value) {} 660 660 661 661 EdgeMap& operator=(const EdgeMap& cmap) { 662 662 return operator=<EdgeMap>(cmap); 663 663 } 664 664 … … 666 666 EdgeMap& operator=(const CMap& cmap) { 667 667 Parent::operator=(cmap); 668 668 return *this; 669 669 } 670 670 … … 684 684 std::vector<Arc> ev; 685 685 ev.push_back(Parent::direct(edge, true)); 686 ev.push_back(Parent::direct(edge, false)); 686 ev.push_back(Parent::direct(edge, false)); 687 687 notifier(Arc()).add(ev); 688 688 return edge; 689 689 } 690 690 691 691 void clear() { 692 692 notifier(Arc()).clear(); … … 697 697 698 698 template <typename Graph, typename NodeRefMap, typename EdgeRefMap> 699 void build(const Graph& graph, NodeRefMap& nodeRef, 699 void build(const Graph& graph, NodeRefMap& nodeRef, 700 700 EdgeRefMap& edgeRef) { 701 701 Parent::build(graph, nodeRef, edgeRef); … … 709 709 Parent::firstOut(arc, node); 710 710 while (arc != INVALID ) { 711 712 713 } 711 erase(arc); 712 Parent::firstOut(arc, node); 713 } 714 714 715 715 Parent::firstIn(arc, node); 716 716 while (arc != INVALID ) { 717 718 717 erase(arc); 718 Parent::firstIn(arc, node); 719 719 } 720 720 … … 726 726 std::vector<Arc> av; 727 727 av.push_back(Parent::direct(edge, true)); 728 av.push_back(Parent::direct(edge, false)); 728 av.push_back(Parent::direct(edge, false)); 729 729 notifier(Arc()).erase(av); 730 730 notifier(Edge()).erase(edge); … … 733 733 734 734 GraphExtender() { 735 node_notifier.setContainer(*this); 735 node_notifier.setContainer(*this); 736 736 arc_notifier.setContainer(*this); 737 737 edge_notifier.setContainer(*this); 738 } 738 } 739 739 740 740 ~GraphExtender() { 741 741 edge_notifier.clear(); 742 742 arc_notifier.clear(); 743 node_notifier.clear(); 744 } 743 node_notifier.clear(); 744 } 745 745 746 746 }; -
lemon/bits/invalid.h
r49 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 35 35 bool operator< (Invalid) { return false; } 36 36 }; 37 37 38 38 /// \brief Invalid iterators. 39 39 /// … … 53 53 54 54 #endif 55 55 -
lemon/bits/map_extender.h
r107 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 33 33 34 34 /// \ingroup graphbits 35 /// 35 /// 36 36 /// \brief Extender for maps 37 37 template <typename _Map> … … 57 57 public: 58 58 59 MapExtender(const Graph& graph) 59 MapExtender(const Graph& graph) 60 60 : Parent(graph) {} 61 61 62 MapExtender(const Graph& graph, const Value& value) 62 MapExtender(const Graph& graph, const Value& value) 63 63 : Parent(graph, value) {} 64 64 … … 71 71 Parent::operator=(cmap); 72 72 return *this; 73 } 73 } 74 74 75 75 class MapIt : public Item { 76 76 public: 77 77 78 78 typedef Item Parent; 79 79 typedef typename Map::Value Value; 80 80 81 81 MapIt() {} 82 82 … … 87 87 } 88 88 89 MapIt(const Map& _map, const Item& item) 90 91 92 MapIt& operator++() { 93 94 return *this; 95 } 96 89 MapIt(const Map& _map, const Item& item) 90 : Parent(item), map(_map) {} 91 92 MapIt& operator++() { 93 map.notifier()->next(*this); 94 return *this; 95 } 96 97 97 typename MapTraits<Map>::ConstReturnValue operator*() const { 98 98 return map[*this]; 99 99 } 100 100 101 101 typename MapTraits<Map>::ReturnValue operator*() { 102 103 } 104 102 return map[*this]; 103 } 104 105 105 void set(const Value& value) { 106 107 } 108 106 map.set(*this, value); 107 } 108 109 109 protected: 110 110 Map& map; 111 111 112 112 }; 113 113 … … 118 118 119 119 typedef typename Map::Value Value; 120 120 121 121 ConstMapIt() {} 122 122 … … 127 127 } 128 128 129 ConstMapIt(const Map& _map, const Item& item) 130 131 132 ConstMapIt& operator++() { 133 134 return *this; 129 ConstMapIt(const Map& _map, const Item& item) 130 : Parent(item), map(_map) {} 131 132 ConstMapIt& operator++() { 133 map.notifier()->next(*this); 134 return *this; 135 135 } 136 136 137 137 typename MapTraits<Map>::ConstReturnValue operator*() const { 138 138 return map[*this]; 139 139 } 140 140 … … 145 145 class ItemIt : public Item { 146 146 public: 147 148 typedef Item Parent; 149 147 148 typedef Item Parent; 149 150 150 ItemIt() {} 151 151 … … 156 156 } 157 157 158 ItemIt(const Map& _map, const Item& item) 159 160 161 ItemIt& operator++() { 162 163 return *this; 158 ItemIt(const Map& _map, const Item& item) 159 : Parent(item), map(_map) {} 160 161 ItemIt& operator++() { 162 map.notifier()->next(*this); 163 return *this; 164 164 } 165 165 166 166 protected: 167 167 const Map& map; 168 168 169 169 }; 170 170 }; 171 171 172 172 /// \ingroup graphbits 173 /// 173 /// 174 174 /// \brief Extender for maps which use a subset of the items. 175 175 template <typename _Graph, typename _Map> … … 195 195 public: 196 196 197 SubMapExtender(const Graph& _graph) 197 SubMapExtender(const Graph& _graph) 198 198 : Parent(_graph), graph(_graph) {} 199 199 200 SubMapExtender(const Graph& _graph, const Value& _value) 200 SubMapExtender(const Graph& _graph, const Value& _value) 201 201 : Parent(_graph, _value), graph(_graph) {} 202 202 … … 213 213 } 214 214 return *this; 215 } 215 } 216 216 217 217 class MapIt : public Item { 218 218 public: 219 219 220 220 typedef Item Parent; 221 221 typedef typename Map::Value Value; 222 222 223 223 MapIt() {} 224 224 … … 229 229 } 230 230 231 MapIt(const Map& _map, const Item& item) 232 233 234 MapIt& operator++() { 235 236 return *this; 237 } 238 231 MapIt(const Map& _map, const Item& item) 232 : Parent(item), map(_map) {} 233 234 MapIt& operator++() { 235 map.graph.next(*this); 236 return *this; 237 } 238 239 239 typename MapTraits<Map>::ConstReturnValue operator*() const { 240 240 return map[*this]; 241 241 } 242 242 243 243 typename MapTraits<Map>::ReturnValue operator*() { 244 245 } 246 244 return map[*this]; 245 } 246 247 247 void set(const Value& value) { 248 249 } 250 248 map.set(*this, value); 249 } 250 251 251 protected: 252 252 Map& map; 253 253 254 254 }; 255 255 … … 260 260 261 261 typedef typename Map::Value Value; 262 262 263 263 ConstMapIt() {} 264 264 … … 269 269 } 270 270 271 ConstMapIt(const Map& _map, const Item& item) 272 273 274 ConstMapIt& operator++() { 275 276 return *this; 271 ConstMapIt(const Map& _map, const Item& item) 272 : Parent(item), map(_map) {} 273 274 ConstMapIt& operator++() { 275 map.graph.next(*this); 276 return *this; 277 277 } 278 278 279 279 typename MapTraits<Map>::ConstReturnValue operator*() const { 280 280 return map[*this]; 281 281 } 282 282 … … 287 287 class ItemIt : public Item { 288 288 public: 289 290 typedef Item Parent; 291 289 290 typedef Item Parent; 291 292 292 ItemIt() {} 293 293 … … 298 298 } 299 299 300 ItemIt(const Map& _map, const Item& item) 301 302 303 ItemIt& operator++() { 304 305 return *this; 300 ItemIt(const Map& _map, const Item& item) 301 : Parent(item), map(_map) {} 302 303 ItemIt& operator++() { 304 map.graph.next(*this); 305 return *this; 306 306 } 307 307 308 308 protected: 309 309 const Map& map; 310 311 }; 312 310 311 }; 312 313 313 private: 314 314 315 315 const Graph& graph; 316 316 317 317 }; 318 318 -
lemon/bits/path_dump.h
r100 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 54 54 RevArcIt() {} 55 55 RevArcIt(Invalid) : path(0), current(INVALID) {} 56 RevArcIt(const PredMapPath& _path) 56 RevArcIt(const PredMapPath& _path) 57 57 : path(&_path), current(_path.target) { 58 58 if (path->predMap[current] == INVALID) current = INVALID; … … 69 69 } 70 70 71 bool operator==(const RevArcIt& e) const { 72 return current == e.current; 71 bool operator==(const RevArcIt& e) const { 72 return current == e.current; 73 73 } 74 74 75 75 bool operator!=(const RevArcIt& e) const { 76 return current != e.current; 76 return current != e.current; 77 77 } 78 78 79 bool operator<(const RevArcIt& e) const { 80 return current < e.current; 79 bool operator<(const RevArcIt& e) const { 80 return current < e.current; 81 81 } 82 82 83 83 private: 84 84 const PredMapPath* path; … … 102 102 typedef _PredMatrixMap PredMatrixMap; 103 103 104 PredMatrixMapPath(const Digraph& _digraph, 104 PredMatrixMapPath(const Digraph& _digraph, 105 105 const PredMatrixMap& _predMatrixMap, 106 typename Digraph::Node _source, 106 typename Digraph::Node _source, 107 107 typename Digraph::Node _target) 108 : digraph(_digraph), predMatrixMap(_predMatrixMap), 108 : digraph(_digraph), predMatrixMap(_predMatrixMap), 109 109 source(_source), target(_target) {} 110 110 … … 128 128 RevArcIt() {} 129 129 RevArcIt(Invalid) : path(0), current(INVALID) {} 130 RevArcIt(const PredMatrixMapPath& _path) 130 RevArcIt(const PredMatrixMapPath& _path) 131 131 : path(&_path), current(_path.target) { 132 if (path->predMatrixMap(path->source, current) == INVALID) 132 if (path->predMatrixMap(path->source, current) == INVALID) 133 133 current = INVALID; 134 134 } … … 139 139 140 140 RevArcIt& operator++() { 141 current = 141 current = 142 142 path->digraph.source(path->predMatrixMap(path->source, current)); 143 if (path->predMatrixMap(path->source, current) == INVALID) 143 if (path->predMatrixMap(path->source, current) == INVALID) 144 144 current = INVALID; 145 145 return *this; 146 146 } 147 147 148 bool operator==(const RevArcIt& e) const { 149 return current == e.current; 148 bool operator==(const RevArcIt& e) const { 149 return current == e.current; 150 150 } 151 151 152 152 bool operator!=(const RevArcIt& e) const { 153 return current != e.current; 153 return current != e.current; 154 154 } 155 155 156 bool operator<(const RevArcIt& e) const { 157 return current < e.current; 156 bool operator<(const RevArcIt& e) const { 157 return current < e.current; 158 158 } 159 159 160 160 private: 161 161 const PredMatrixMapPath* path; -
lemon/bits/traits.h
r184 r209 1 2 /* -*- C++ -*- 3 * 4 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 5 4 * 6 5 * Copyright (C) 2003-2008 … … 30 29 template <typename _Graph, typename _Item> 31 30 class ItemSetTraits {}; 32 31 33 32 34 33 template <typename Graph, typename Enable = void> … … 38 37 template <typename Graph> 39 38 struct NodeNotifierIndicator< 40 Graph, 39 Graph, 41 40 typename enable_if<typename Graph::NodeNotifier::Notifier, void>::type 42 > { 41 > { 43 42 typedef typename Graph::NodeNotifier Type; 44 43 }; … … 47 46 class ItemSetTraits<_Graph, typename _Graph::Node> { 48 47 public: 49 48 50 49 typedef _Graph Graph; 51 50 … … 58 57 class Map : public Graph::template NodeMap<_Value> { 59 58 public: 60 typedef typename Graph::template NodeMap<_Value> Parent; 61 typedef typename Graph::template NodeMap<_Value> Type; 59 typedef typename Graph::template NodeMap<_Value> Parent; 60 typedef typename Graph::template NodeMap<_Value> Type; 62 61 typedef typename Parent::Value Value; 63 62 64 63 Map(const Graph& _digraph) : Parent(_digraph) {} 65 Map(const Graph& _digraph, const Value& _value) 66 64 Map(const Graph& _digraph, const Value& _value) 65 : Parent(_digraph, _value) {} 67 66 68 67 }; … … 76 75 template <typename Graph> 77 76 struct ArcNotifierIndicator< 78 Graph, 77 Graph, 79 78 typename enable_if<typename Graph::ArcNotifier::Notifier, void>::type 80 > { 79 > { 81 80 typedef typename Graph::ArcNotifier Type; 82 81 }; … … 85 84 class ItemSetTraits<_Graph, typename _Graph::Arc> { 86 85 public: 87 86 88 87 typedef _Graph Graph; 89 88 … … 96 95 class Map : public Graph::template ArcMap<_Value> { 97 96 public: 98 typedef typename Graph::template ArcMap<_Value> Parent; 99 typedef typename Graph::template ArcMap<_Value> Type; 97 typedef typename Graph::template ArcMap<_Value> Parent; 98 typedef typename Graph::template ArcMap<_Value> Type; 100 99 typedef typename Parent::Value Value; 101 100 102 101 Map(const Graph& _digraph) : Parent(_digraph) {} 103 Map(const Graph& _digraph, const Value& _value) 104 102 Map(const Graph& _digraph, const Value& _value) 103 : Parent(_digraph, _value) {} 105 104 }; 106 105 … … 113 112 template <typename Graph> 114 113 struct EdgeNotifierIndicator< 115 Graph, 114 Graph, 116 115 typename enable_if<typename Graph::EdgeNotifier::Notifier, void>::type 117 > { 116 > { 118 117 typedef typename Graph::EdgeNotifier Type; 119 118 }; … … 122 121 class ItemSetTraits<_Graph, typename _Graph::Edge> { 123 122 public: 124 123 125 124 typedef _Graph Graph; 126 125 … … 133 132 class Map : public Graph::template EdgeMap<_Value> { 134 133 public: 135 typedef typename Graph::template EdgeMap<_Value> Parent; 136 typedef typename Graph::template EdgeMap<_Value> Type; 134 typedef typename Graph::template EdgeMap<_Value> Parent; 135 typedef typename Graph::template EdgeMap<_Value> Type; 137 136 typedef typename Parent::Value Value; 138 137 139 138 Map(const Graph& _digraph) : Parent(_digraph) {} 140 Map(const Graph& _digraph, const Value& _value) 141 139 Map(const Graph& _digraph, const Value& _value) 140 : Parent(_digraph, _value) {} 142 141 }; 143 142 … … 157 156 template <typename Map> 158 157 struct MapTraits< 159 Map, typename enable_if<typename Map::ReferenceMapTag, void>::type > 158 Map, typename enable_if<typename Map::ReferenceMapTag, void>::type > 160 159 { 161 160 typedef True ReferenceMapTag; 162 161 163 162 typedef typename Map::Key Key; 164 163 typedef typename Map::Value Value; … … 167 166 typedef typename Map::Reference ReturnValue; 168 167 169 typedef typename Map::ConstReference ConstReference; 168 typedef typename Map::ConstReference ConstReference; 170 169 typedef typename Map::Reference Reference; 171 170 }; … … 185 184 template <typename MatrixMap> 186 185 struct MatrixMapTraits< 187 MatrixMap, typename enable_if<typename MatrixMap::ReferenceMapTag, 188 void>::type > 186 MatrixMap, typename enable_if<typename MatrixMap::ReferenceMapTag, 187 void>::type > 189 188 { 190 189 typedef True ReferenceMapTag; 191 190 192 191 typedef typename MatrixMap::FirstKey FirstKey; 193 192 typedef typename MatrixMap::SecondKey SecondKey; … … 197 196 typedef typename MatrixMap::Reference ReturnValue; 198 197 199 typedef typename MatrixMap::ConstReference ConstReference; 198 typedef typename MatrixMap::ConstReference ConstReference; 200 199 typedef typename MatrixMap::Reference Reference; 201 200 }; … … 210 209 template <typename Graph> 211 210 struct NodeNumTagIndicator< 212 Graph, 211 Graph, 213 212 typename enable_if<typename Graph::NodeNumTag, void>::type 214 213 > { … … 223 222 template <typename Graph> 224 223 struct EdgeNumTagIndicator< 225 Graph, 224 Graph, 226 225 typename enable_if<typename Graph::EdgeNumTag, void>::type 227 226 > { … … 236 235 template <typename Graph> 237 236 struct FindEdgeTagIndicator< 238 Graph, 237 Graph, 239 238 typename enable_if<typename Graph::FindEdgeTag, void>::type 240 239 > { … … 249 248 template <typename Graph> 250 249 struct UndirectedTagIndicator< 251 Graph, 250 Graph, 252 251 typename enable_if<typename Graph::UndirectedTag, void>::type 253 252 > { … … 262 261 template <typename Graph> 263 262 struct BuildTagIndicator< 264 Graph, 263 Graph, 265 264 typename enable_if<typename Graph::BuildTag, void>::type 266 265 > { -
lemon/bits/utility.h
r117 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 84 84 85 85 /**************** enable_if from BOOST ****************/ 86 86 87 87 template <typename Type, typename T = void> 88 88 struct exists { … … 90 90 }; 91 91 92 92 93 93 template <bool B, class T = void> 94 94 struct enable_if_c { … … 99 99 struct enable_if_c<false, T> {}; 100 100 101 template <class Cond, class T = void> 101 template <class Cond, class T = void> 102 102 struct enable_if : public enable_if_c<Cond::value, T> {}; 103 103 … … 110 110 struct lazy_enable_if_c<false, T> {}; 111 111 112 template <class Cond, class T> 112 template <class Cond, class T> 113 113 struct lazy_enable_if : public lazy_enable_if_c<Cond::value, T> {}; 114 114 … … 122 122 struct disable_if_c<true, T> {}; 123 123 124 template <class Cond, class T = void> 124 template <class Cond, class T = void> 125 125 struct disable_if : public disable_if_c<Cond::value, T> {}; 126 126 … … 133 133 struct lazy_disable_if_c<true, T> {}; 134 134 135 template <class Cond, class T> 135 template <class Cond, class T> 136 136 struct lazy_disable_if : public lazy_disable_if_c<Cond::value, T> {}; 137 137 -
lemon/bits/vector_map.h
r157 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 50 50 /// \todo Fix the doc: there is _Graph parameter instead of _Notifier. 51 51 template <typename _Graph, typename _Item, typename _Value> 52 class VectorMap 52 class VectorMap 53 53 : public ItemSetTraits<_Graph, _Item>::ItemNotifier::ObserverBase { 54 54 private: 55 55 56 56 /// The container type of the map. 57 typedef std::vector<_Value> Container; 57 typedef std::vector<_Value> Container; 58 58 59 59 public: 60 60 61 /// The graph type of the map. 61 /// The graph type of the map. 62 62 typedef _Graph Graph; 63 63 /// The item type of the map. … … 94 94 } 95 95 96 /// \brief Constructor uses given value to initialize the map. 97 /// 98 /// It constructs a map uses a given value to initialize the map. 96 /// \brief Constructor uses given value to initialize the map. 97 /// 98 /// It constructs a map uses a given value to initialize the map. 99 99 /// It adds all the items of the graph to the map. 100 100 VectorMap(const Graph& graph, const Value& value) { … … 108 108 VectorMap(const VectorMap& _copy) : Parent() { 109 109 if (_copy.attached()) { 110 111 110 Parent::attach(*_copy.notifier()); 111 container = _copy.container; 112 112 } 113 113 } … … 116 116 /// 117 117 /// This operator assigns for each item in the map the 118 /// value mapped to the same item in the copied map. 118 /// value mapped to the same item in the copied map. 119 119 /// The parameter map should be indiced with the same 120 120 /// itemset because this assign operator does not change 121 /// the container of the map. 121 /// the container of the map. 122 122 VectorMap& operator=(const VectorMap& cmap) { 123 123 return operator=<VectorMap>(cmap); … … 130 130 /// concecpt and could be indiced by the current item set of 131 131 /// the NodeMap. In this case the value for each item 132 /// is assigned by the value of the given ReadMap. 132 /// is assigned by the value of the given ReadMap. 133 133 template <typename CMap> 134 134 VectorMap& operator=(const CMap& cmap) { … … 141 141 return *this; 142 142 } 143 143 144 144 public: 145 145 … … 147 147 /// 148 148 /// The subscript operator. The map can be subscripted by the 149 /// actual items of the graph. 149 /// actual items of the graph. 150 150 Reference operator[](const Key& key) { 151 151 return container[Parent::notifier()->id(key)]; 152 } 153 152 } 153 154 154 /// \brief The const subcript operator. 155 155 /// 156 156 /// The const subscript operator. The map can be subscripted by the 157 /// actual items of the graph. 157 /// actual items of the graph. 158 158 ConstReference operator[](const Key& key) const { 159 159 return container[Parent::notifier()->id(key)]; … … 171 171 172 172 /// \brief Adds a new key to the map. 173 /// 173 /// 174 174 /// It adds a new key to the map. It called by the observer notifier 175 /// and it overrides the add() member function of the observer base. 175 /// and it overrides the add() member function of the observer base. 176 176 virtual void add(const Key& key) { 177 177 int id = Parent::notifier()->id(key); 178 178 if (id >= int(container.size())) { 179 179 container.resize(id + 1); 180 180 } 181 181 } 182 182 183 183 /// \brief Adds more new keys to the map. 184 /// 184 /// 185 185 /// It adds more new keys to the map. It called by the observer notifier 186 /// and it overrides the add() member function of the observer base. 186 /// and it overrides the add() member function of the observer base. 187 187 virtual void add(const std::vector<Key>& keys) { 188 188 int max = container.size() - 1; … … 199 199 /// 200 200 /// Erase a key from the map. It called by the observer notifier 201 /// and it overrides the erase() member function of the observer base. 201 /// and it overrides the erase() member function of the observer base. 202 202 virtual void erase(const Key& key) { 203 203 container[Parent::notifier()->id(key)] = Value(); … … 207 207 /// 208 208 /// Erase more keys from the map. It called by the observer notifier 209 /// and it overrides the erase() member function of the observer base. 209 /// and it overrides the erase() member function of the observer base. 210 210 virtual void erase(const std::vector<Key>& keys) { 211 211 for (int i = 0; i < int(keys.size()); ++i) { 212 213 } 214 } 215 212 container[Parent::notifier()->id(keys[i])] = Value(); 213 } 214 } 215 216 216 /// \brief Buildes the map. 217 /// 217 /// 218 218 /// It buildes the map. It called by the observer notifier 219 219 /// and it overrides the build() member function of the observer base. 220 virtual void build() { 220 virtual void build() { 221 221 int size = Parent::notifier()->maxId() + 1; 222 222 container.reserve(size); … … 227 227 /// 228 228 /// It erase all items from the map. It called by the observer notifier 229 /// and it overrides the clear() member function of the observer base. 230 virtual void clear() { 229 /// and it overrides the clear() member function of the observer base. 230 virtual void clear() { 231 231 container.clear(); 232 232 } 233 233 234 234 private: 235 235 236 236 Container container; 237 237 -
lemon/color.cc
r128 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 25 25 26 26 const Color WHITE(1,1,1); 27 27 28 28 const Color BLACK(0,0,0); 29 29 const Color RED(1,0,0); … … 41 41 const Color DARK_MAGENTA(.5,0,.5); 42 42 const Color DARK_CYAN(0,.5,.5); 43 43 44 44 } //namespace lemon -
lemon/color.h
r206 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 63 63 64 64 /// White color constant 65 extern const Color WHITE; 65 extern const Color WHITE; 66 66 /// Black color constant 67 67 extern const Color BLACK; … … 131 131 colors.push_back(Color(1,0,1)); 132 132 colors.push_back(Color(0,1,1)); 133 133 134 134 colors.push_back(Color(.5,0,0)); 135 135 colors.push_back(Color(0,.5,0)); … … 138 138 colors.push_back(Color(.5,0,.5)); 139 139 colors.push_back(Color(0,.5,.5)); 140 140 141 141 colors.push_back(Color(.5,.5,.5)); 142 142 colors.push_back(Color(1,.5,.5)); … … 146 146 colors.push_back(Color(1,.5,1)); 147 147 colors.push_back(Color(.5,1,1)); 148 148 149 149 colors.push_back(Color(1,.5,0)); 150 150 colors.push_back(Color(.5,1,0)); … … 172 172 } 173 173 ///Adds a new color to the end of the color list. 174 void add(const Color &c) 174 void add(const Color &c) 175 175 { 176 176 colors.push_back(c); … … 187 187 ///Returns a \ref Color which is as different from the given parameter 188 188 ///as it is possible. 189 inline Color distantColor(const Color &c) 189 inline Color distantColor(const Color &c) 190 190 { 191 191 return Color(c.red()<.5?1:0,c.green()<.5?1:0,c.blue()<.5?1:0); -
lemon/concept_check.h
r53 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 37 37 ///\brief Basic utilities for concept checking. 38 38 /// 39 ///\todo Are we still using BOOST concept checking utility? 39 ///\todo Are we still using BOOST concept checking utility? 40 40 ///Is the BOOST copyright notice necessary? 41 41 -
lemon/concepts/digraph.h
r125 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 47 47 private: 48 48 ///Digraphs are \e not copy constructible. Use DigraphCopy() instead. 49 49 50 50 ///Digraphs are \e not copy constructible. Use DigraphCopy() instead. 51 51 /// … … 53 53 ///\brief Assignment of \ref Digraph "Digraph"s to another ones are 54 54 ///\e not allowed. Use DigraphCopy() instead. 55 55 56 56 ///Assignment of \ref Digraph "Digraph"s to another ones are 57 57 ///\e not allowed. Use DigraphCopy() instead. … … 96 96 97 97 /// Inequality operator 98 98 99 99 /// \sa operator==(Node n) 100 100 /// 101 101 bool operator!=(Node) const { return true; } 102 102 103 104 105 106 107 108 109 110 111 112 113 }; 114 103 /// Artificial ordering operator. 104 105 /// To allow the use of digraph descriptors as key type in std::map or 106 /// similar associative container we require this. 107 /// 108 /// \note This operator only have to define some strict ordering of 109 /// the items; this order has nothing to do with the iteration 110 /// ordering of the items. 111 bool operator<(Node) const { return false; } 112 113 }; 114 115 115 /// This iterator goes through each node. 116 116 … … 130 130 NodeIt() { } 131 131 /// Copy constructor. 132 132 133 133 /// Copy constructor. 134 134 /// … … 146 146 /// Node -> NodeIt conversion. 147 147 148 /// Sets the iterator to the node of \c the digraph pointed by 149 150 /// This feature necessitates that each time we 148 /// Sets the iterator to the node of \c the digraph pointed by 149 /// the trivial iterator. 150 /// This feature necessitates that each time we 151 151 /// iterate the arc-set, the iteration order is the same. 152 152 NodeIt(const Digraph&, const Node&) { } … … 157 157 NodeIt& operator++() { return *this; } 158 158 }; 159 160 159 160 161 161 /// Class for identifying an arc of the digraph 162 162 … … 192 192 bool operator!=(Arc) const { return true; } 193 193 194 195 196 197 198 199 200 201 202 203 }; 204 194 /// Artificial ordering operator. 195 196 /// To allow the use of digraph descriptors as key type in std::map or 197 /// similar associative container we require this. 198 /// 199 /// \note This operator only have to define some strict ordering of 200 /// the items; this order has nothing to do with the iteration 201 /// ordering of the items. 202 bool operator<(Arc) const { return false; } 203 }; 204 205 205 /// This iterator goes trough the outgoing arcs of a node. 206 206 … … 214 214 /// for (Digraph::OutArcIt e(g, n); e!=INVALID; ++e) ++count; 215 215 ///\endcode 216 216 217 217 class OutArcIt : public Arc { 218 218 public: … … 233 233 OutArcIt(Invalid) { } 234 234 /// This constructor sets the iterator to the first outgoing arc. 235 235 236 236 /// This constructor sets the iterator to the first outgoing arc of 237 237 /// the node. … … 240 240 241 241 /// Sets the iterator to the value of the trivial iterator. 242 /// This feature necessitates that each time we 242 /// This feature necessitates that each time we 243 243 /// iterate the arc-set, the iteration order is the same. 244 244 OutArcIt(const Digraph&, const Arc&) { } 245 245 ///Next outgoing arc 246 247 /// Assign the iterator to the next 246 247 /// Assign the iterator to the next 248 248 /// outgoing arc of the corresponding node. 249 249 OutArcIt& operator++() { return *this; } … … 280 280 InArcIt(Invalid) { } 281 281 /// This constructor sets the iterator to first incoming arc. 282 282 283 283 /// This constructor set the iterator to the first incoming arc of 284 284 /// the node. … … 287 287 288 288 /// Sets the iterator to the value of the trivial iterator \c e. 289 /// This feature necessitates that each time we 289 /// This feature necessitates that each time we 290 290 /// iterate the arc-set, the iteration order is the same. 291 291 InArcIt(const Digraph&, const Arc&) { } … … 323 323 ArcIt(Invalid) { } 324 324 /// This constructor sets the iterator to the first arc. 325 325 326 326 /// This constructor sets the iterator to the first arc of \c g. 327 327 ///@param g the digraph … … 330 330 331 331 /// Sets the iterator to the value of the trivial iterator \c e. 332 /// This feature necessitates that each time we 332 /// This feature necessitates that each time we 333 333 /// iterate the arc-set, the iteration order is the same. 334 ArcIt(const Digraph&, const Arc&) { } 334 ArcIt(const Digraph&, const Arc&) { } 335 335 ///Next arc 336 336 337 337 /// Assign the iterator to the next arc. 338 338 ArcIt& operator++() { return *this; } … … 350 350 351 351 /// \brief Returns the ID of the node. 352 int id(Node) const { return -1; } 352 int id(Node) const { return -1; } 353 353 354 354 /// \brief Returns the ID of the arc. 355 int id(Arc) const { return -1; } 355 int id(Arc) const { return -1; } 356 356 357 357 /// \brief Returns the node with the given ID. 358 358 /// 359 359 /// \pre The argument should be a valid node ID in the graph. 360 Node nodeFromId(int) const { return INVALID; } 360 Node nodeFromId(int) const { return INVALID; } 361 361 362 362 /// \brief Returns the arc with the given ID. 363 363 /// 364 364 /// \pre The argument should be a valid arc ID in the graph. 365 Arc arcFromId(int) const { return INVALID; } 365 Arc arcFromId(int) const { return INVALID; } 366 366 367 367 /// \brief Returns an upper bound on the node IDs. 368 int maxNodeId() const { return -1; } 368 int maxNodeId() const { return -1; } 369 369 370 370 /// \brief Returns an upper bound on the arc IDs. 371 int maxArcId() const { return -1; } 371 int maxArcId() const { return -1; } 372 372 373 373 void first(Node&) const {} … … 390 390 391 391 // Dummy parameter. 392 int maxId(Node) const { return -1; } 392 int maxId(Node) const { return -1; } 393 393 // Dummy parameter. 394 int maxId(Arc) const { return -1; } 394 int maxId(Arc) const { return -1; } 395 395 396 396 /// \brief The base node of the iterator. … … 424 424 425 425 /// \brief Read write map of the nodes to type \c T. 426 /// 426 /// 427 427 /// ReadWrite map of the nodes to type \c T. 428 428 /// \sa Reference 429 template<class T> 429 template<class T> 430 430 class NodeMap : public ReadWriteMap< Node, T > { 431 431 public: … … 440 440 ///Assignment operator 441 441 template <typename CMap> 442 NodeMap& operator=(const CMap&) { 442 NodeMap& operator=(const CMap&) { 443 443 checkConcept<ReadMap<Node, T>, CMap>(); 444 return *this; 444 return *this; 445 445 } 446 446 }; … … 450 450 /// Reference map of the arcs to type \c T. 451 451 /// \sa Reference 452 template<class T> 452 template<class T> 453 453 class ArcMap : public ReadWriteMap<Arc,T> { 454 454 public: … … 462 462 ///Assignment operator 463 463 template <typename CMap> 464 ArcMap& operator=(const CMap&) { 464 ArcMap& operator=(const CMap&) { 465 465 checkConcept<ReadMap<Arc, T>, CMap>(); 466 return *this; 466 return *this; 467 467 } 468 468 }; … … 472 472 void constraints() { 473 473 checkConcept<IterableDigraphComponent<>, _Digraph>(); 474 474 checkConcept<IDableDigraphComponent<>, _Digraph>(); 475 475 checkConcept<MappableDigraphComponent<>, _Digraph>(); 476 476 } … … 478 478 479 479 }; 480 481 } //namespace concepts 480 481 } //namespace concepts 482 482 } //namespace lemon 483 483 -
lemon/concepts/graph.h
r125 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 66 66 /// direction. The IncEdgeIt iterates also on the same edges 67 67 /// as the OutArcIt and InArcIt but it is not convertible to Arc just 68 /// to Edge. 68 /// to Edge. 69 69 class Graph { 70 70 public: … … 73 73 /// 74 74 /// The undirected graph should be tagged by the UndirectedTag. This 75 /// tag helps the enable_if technics to make compile time 76 /// specializations for undirected graphs. 75 /// tag helps the enable_if technics to make compile time 76 /// specializations for undirected graphs. 77 77 typedef True UndirectedTag; 78 78 79 /// \brief The base type of node iterators, 79 /// \brief The base type of node iterators, 80 80 /// or in other words, the trivial node iterator. 81 81 /// 82 82 /// This is the base type of each node iterator, 83 83 /// thus each kind of node iterator converts to this. 84 /// More precisely each kind of node iterator should be inherited 84 /// More precisely each kind of node iterator should be inherited 85 85 /// from the trivial node iterator. 86 86 class Node { … … 109 109 110 110 /// Inequality operator 111 111 112 112 /// \sa operator==(Node n) 113 113 /// 114 114 bool operator!=(Node) const { return true; } 115 115 116 117 118 119 120 121 122 123 124 125 126 }; 127 116 /// Artificial ordering operator. 117 118 /// To allow the use of graph descriptors as key type in std::map or 119 /// similar associative container we require this. 120 /// 121 /// \note This operator only have to define some strict ordering of 122 /// the items; this order has nothing to do with the iteration 123 /// ordering of the items. 124 bool operator<(Node) const { return false; } 125 126 }; 127 128 128 /// This iterator goes through each node. 129 129 … … 143 143 NodeIt() { } 144 144 /// Copy constructor. 145 145 146 146 /// Copy constructor. 147 147 /// … … 159 159 /// Node -> NodeIt conversion. 160 160 161 /// Sets the iterator to the node of \c the graph pointed by 162 163 /// This feature necessitates that each time we 161 /// Sets the iterator to the node of \c the graph pointed by 162 /// the trivial iterator. 163 /// This feature necessitates that each time we 164 164 /// iterate the arc-set, the iteration order is the same. 165 165 NodeIt(const Graph&, const Node&) { } … … 170 170 NodeIt& operator++() { return *this; } 171 171 }; 172 173 172 173 174 174 /// The base type of the edge iterators. 175 175 … … 204 204 bool operator!=(Edge) const { return true; } 205 205 206 207 208 209 210 211 212 213 214 206 /// Artificial ordering operator. 207 208 /// To allow the use of graph descriptors as key type in std::map or 209 /// similar associative container we require this. 210 /// 211 /// \note This operator only have to define some strict ordering of 212 /// the items; this order has nothing to do with the iteration 213 /// ordering of the items. 214 bool operator<(Edge) const { return false; } 215 215 }; 216 216 … … 242 242 EdgeIt(Invalid) { } 243 243 /// This constructor sets the iterator to the first edge. 244 244 245 245 /// This constructor sets the iterator to the first edge. 246 246 EdgeIt(const Graph&) { } … … 249 249 /// Sets the iterator to the value of the trivial iterator. 250 250 /// This feature necessitates that each time we 251 /// iterate the edge-set, the iteration order is the 252 253 EdgeIt(const Graph&, const Edge&) { } 251 /// iterate the edge-set, the iteration order is the 252 /// same. 253 EdgeIt(const Graph&, const Edge&) { } 254 254 /// Next edge 255 255 256 256 /// Assign the iterator to the next edge. 257 257 EdgeIt& operator++() { return *this; } 258 258 }; 259 259 260 /// \brief This iterator goes trough the incident undirected 260 /// \brief This iterator goes trough the incident undirected 261 261 /// arcs of a node. 262 262 /// 263 263 /// This iterator goes trough the incident edges 264 /// of a certain node of a graph. You should assume that the 264 /// of a certain node of a graph. You should assume that the 265 265 /// loop arcs will be iterated twice. 266 /// 266 /// 267 267 /// Its usage is quite simple, for example you can compute the 268 268 /// degree (i.e. count the number of incident arcs of a node \c n 269 /// in graph \c g of type \c Graph as follows. 269 /// in graph \c g of type \c Graph as follows. 270 270 /// 271 271 ///\code … … 291 291 IncEdgeIt(Invalid) { } 292 292 /// This constructor sets the iterator to first incident arc. 293 293 294 294 /// This constructor set the iterator to the first incident arc of 295 295 /// the node. … … 298 298 299 299 /// Sets the iterator to the value of the trivial iterator \c e. 300 /// This feature necessitates that each time we 300 /// This feature necessitates that each time we 301 301 /// iterate the arc-set, the iteration order is the same. 302 302 IncEdgeIt(const Graph&, const Edge&) { } … … 304 304 305 305 /// Assign the iterator to the next incident arc 306 306 /// of the corresponding node. 307 307 IncEdgeIt& operator++() { return *this; } 308 308 }; … … 341 341 bool operator!=(Arc) const { return true; } 342 342 343 344 345 346 347 348 349 350 351 352 353 }; 343 /// Artificial ordering operator. 344 345 /// To allow the use of graph descriptors as key type in std::map or 346 /// similar associative container we require this. 347 /// 348 /// \note This operator only have to define some strict ordering of 349 /// the items; this order has nothing to do with the iteration 350 /// ordering of the items. 351 bool operator<(Arc) const { return false; } 352 353 }; 354 354 /// This iterator goes through each directed arc. 355 355 … … 379 379 ArcIt(Invalid) { } 380 380 /// This constructor sets the iterator to the first arc. 381 381 382 382 /// This constructor sets the iterator to the first arc of \c g. 383 383 ///@param g the graph … … 386 386 387 387 /// Sets the iterator to the value of the trivial iterator \c e. 388 /// This feature necessitates that each time we 388 /// This feature necessitates that each time we 389 389 /// iterate the arc-set, the iteration order is the same. 390 ArcIt(const Graph&, const Arc&) { } 390 ArcIt(const Graph&, const Arc&) { } 391 391 ///Next arc 392 392 393 393 /// Assign the iterator to the next arc. 394 394 ArcIt& operator++() { return *this; } 395 395 }; 396 396 397 397 /// This iterator goes trough the outgoing directed arcs of a node. 398 398 … … 406 406 /// for (Graph::OutArcIt e(g, n); e!=INVALID; ++e) ++count; 407 407 ///\endcode 408 408 409 409 class OutArcIt : public Arc { 410 410 public: … … 425 425 OutArcIt(Invalid) { } 426 426 /// This constructor sets the iterator to the first outgoing arc. 427 427 428 428 /// This constructor sets the iterator to the first outgoing arc of 429 429 /// the node. … … 431 431 ///@param g the graph 432 432 OutArcIt(const Graph& n, const Node& g) { 433 434 435 433 ignore_unused_variable_warning(n); 434 ignore_unused_variable_warning(g); 435 } 436 436 /// Arc -> OutArcIt conversion 437 437 438 438 /// Sets the iterator to the value of the trivial iterator. 439 /// This feature necessitates that each time we 439 /// This feature necessitates that each time we 440 440 /// iterate the arc-set, the iteration order is the same. 441 441 OutArcIt(const Graph&, const Arc&) { } 442 442 ///Next outgoing arc 443 444 /// Assign the iterator to the next 443 444 /// Assign the iterator to the next 445 445 /// outgoing arc of the corresponding node. 446 446 OutArcIt& operator++() { return *this; } … … 477 477 InArcIt(Invalid) { } 478 478 /// This constructor sets the iterator to first incoming arc. 479 479 480 480 /// This constructor set the iterator to the first incoming arc of 481 481 /// the node. 482 482 ///@param n the node 483 483 ///@param g the graph 484 InArcIt(const Graph& g, const Node& n) { 485 486 487 484 InArcIt(const Graph& g, const Node& n) { 485 ignore_unused_variable_warning(n); 486 ignore_unused_variable_warning(g); 487 } 488 488 /// Arc -> InArcIt conversion 489 489 490 490 /// Sets the iterator to the value of the trivial iterator \c e. 491 /// This feature necessitates that each time we 491 /// This feature necessitates that each time we 492 492 /// iterate the arc-set, the iteration order is the same. 493 493 InArcIt(const Graph&, const Arc&) { } … … 500 500 501 501 /// \brief Read write map of the nodes to type \c T. 502 /// 502 /// 503 503 /// ReadWrite map of the nodes to type \c T. 504 504 /// \sa Reference 505 template<class T> 505 template<class T> 506 506 class NodeMap : public ReadWriteMap< Node, T > 507 507 { … … 517 517 ///Assignment operator 518 518 template <typename CMap> 519 NodeMap& operator=(const CMap&) { 519 NodeMap& operator=(const CMap&) { 520 520 checkConcept<ReadMap<Node, T>, CMap>(); 521 return *this; 521 return *this; 522 522 } 523 523 }; … … 527 527 /// Reference map of the directed arcs to type \c T. 528 528 /// \sa Reference 529 template<class T> 529 template<class T> 530 530 class ArcMap : public ReadWriteMap<Arc,T> 531 531 { … … 540 540 ///Assignment operator 541 541 template <typename CMap> 542 ArcMap& operator=(const CMap&) { 542 ArcMap& operator=(const CMap&) { 543 543 checkConcept<ReadMap<Arc, T>, CMap>(); 544 return *this; 544 return *this; 545 545 } 546 546 }; … … 550 550 /// Reference map of the arcs to type \c T. 551 551 /// \sa Reference 552 template<class T> 552 template<class T> 553 553 class EdgeMap : public ReadWriteMap<Edge,T> 554 554 { … … 563 563 ///Assignment operator 564 564 template <typename CMap> 565 EdgeMap& operator=(const CMap&) { 565 EdgeMap& operator=(const CMap&) { 566 566 checkConcept<ReadMap<Edge, T>, CMap>(); 567 return *this; 567 return *this; 568 568 } 569 569 }; … … 574 574 /// will be the given node. 575 575 Arc direct(const Edge&, const Node&) const { 576 576 return INVALID; 577 577 } 578 578 … … 584 584 /// the directed arc is the same when the given bool is true. 585 585 Arc direct(const Edge&, bool) const { 586 586 return INVALID; 587 587 } 588 588 … … 626 626 627 627 /// \brief Returns the id of the node. 628 int id(Node) const { return -1; } 628 int id(Node) const { return -1; } 629 629 630 630 /// \brief Returns the id of the edge. 631 int id(Edge) const { return -1; } 631 int id(Edge) const { return -1; } 632 632 633 633 /// \brief Returns the id of the arc. 634 int id(Arc) const { return -1; } 634 int id(Arc) const { return -1; } 635 635 636 636 /// \brief Returns the node with the given id. 637 637 /// 638 638 /// \pre The argument should be a valid node id in the graph. 639 Node nodeFromId(int) const { return INVALID; } 639 Node nodeFromId(int) const { return INVALID; } 640 640 641 641 /// \brief Returns the edge with the given id. 642 642 /// 643 643 /// \pre The argument should be a valid edge id in the graph. 644 Edge edgeFromId(int) const { return INVALID; } 644 Edge edgeFromId(int) const { return INVALID; } 645 645 646 646 /// \brief Returns the arc with the given id. 647 647 /// 648 648 /// \pre The argument should be a valid arc id in the graph. 649 Arc arcFromId(int) const { return INVALID; } 649 Arc arcFromId(int) const { return INVALID; } 650 650 651 651 /// \brief Returns an upper bound on the node IDs. 652 int maxNodeId() const { return -1; } 652 int maxNodeId() const { return -1; } 653 653 654 654 /// \brief Returns an upper bound on the edge IDs. 655 int maxEdgeId() const { return -1; } 655 int maxEdgeId() const { return -1; } 656 656 657 657 /// \brief Returns an upper bound on the arc IDs. 658 int maxArcId() const { return -1; } 658 int maxArcId() const { return -1; } 659 659 660 660 void first(Node&) const {} … … 684 684 685 685 // Dummy parameter. 686 int maxId(Node) const { return -1; } 686 int maxId(Node) const { return -1; } 687 687 // Dummy parameter. 688 int maxId(Edge) const { return -1; } 688 int maxId(Edge) const { return -1; } 689 689 // Dummy parameter. 690 int maxId(Arc) const { return -1; } 690 int maxId(Arc) const { return -1; } 691 691 692 692 /// \brief Base node of the iterator … … 694 694 /// Returns the base node (the source in this case) of the iterator 695 695 Node baseNode(OutArcIt e) const { 696 696 return source(e); 697 697 } 698 698 /// \brief Running node of the iterator … … 701 701 /// iterator 702 702 Node runningNode(OutArcIt e) const { 703 703 return target(e); 704 704 } 705 705 … … 708 708 /// Returns the base node (the target in this case) of the iterator 709 709 Node baseNode(InArcIt e) const { 710 710 return target(e); 711 711 } 712 712 /// \brief Running node of the iterator … … 715 715 /// iterator 716 716 Node runningNode(InArcIt e) const { 717 717 return source(e); 718 718 } 719 719 … … 722 722 /// Returns the base node of the iterator 723 723 Node baseNode(IncEdgeIt) const { 724 724 return INVALID; 725 725 } 726 726 727 727 /// \brief Running node of the iterator 728 728 /// 729 729 /// Returns the running node of the iterator 730 730 Node runningNode(IncEdgeIt) const { 731 731 return INVALID; 732 732 } 733 733 734 734 template <typename _Graph> 735 735 struct Constraints { 736 737 738 739 740 736 void constraints() { 737 checkConcept<IterableGraphComponent<>, _Graph>(); 738 checkConcept<IDableGraphComponent<>, _Graph>(); 739 checkConcept<MappableGraphComponent<>, _Graph>(); 740 } 741 741 }; 742 742 -
lemon/concepts/graph_components.h
r169 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 50 50 public: 51 51 /// \brief Default constructor. 52 /// 52 /// 53 53 /// \warning The default constructor is not required to set 54 54 /// the item to some well-defined value. So you should consider it … … 67 67 /// \brief Assign operator for nodes. 68 68 /// 69 /// The nodes are assignable. 69 /// The nodes are assignable. 70 70 /// 71 71 GraphItem& operator=(GraphItem const&) { return *this; } … … 93 93 template<typename _GraphItem> 94 94 struct Constraints { 95 96 97 98 99 100 101 102 103 //b = (ia == ib) && (ia != ib) && (ia < ib);104 105 95 void constraints() { 96 _GraphItem i1; 97 _GraphItem i2 = i1; 98 _GraphItem i3 = INVALID; 99 100 i1 = i2 = i3; 101 102 bool b; 103 // b = (ia == ib) && (ia != ib) && (ia < ib); 104 b = (ia == ib) && (ia != ib); 105 b = (ia == INVALID) && (ib != INVALID); 106 106 b = (ia < ib); 107 108 109 110 107 } 108 109 const _GraphItem &ia; 110 const _GraphItem &ib; 111 111 }; 112 112 }; 113 113 114 114 /// \brief An empty base directed graph class. 115 /// 115 /// 116 116 /// This class provides the minimal set of features needed for a 117 117 /// directed graph structure. All digraph concepts have to be … … 123 123 124 124 typedef BaseDigraphComponent Digraph; 125 125 126 126 /// \brief Node class of the digraph. 127 127 /// 128 /// This class represents the Nodes of the digraph. 128 /// This class represents the Nodes of the digraph. 129 129 /// 130 130 typedef GraphItem<'n'> Node; … … 132 132 /// \brief Arc class of the digraph. 133 133 /// 134 /// This class represents the Arcs of the digraph. 134 /// This class represents the Arcs of the digraph. 135 135 /// 136 136 typedef GraphItem<'e'> Arc; … … 157 157 template <typename _Digraph> 158 158 struct Constraints { 159 160 161 162 163 164 165 166 167 168 169 159 typedef typename _Digraph::Node Node; 160 typedef typename _Digraph::Arc Arc; 161 162 void constraints() { 163 checkConcept<GraphItem<'n'>, Node>(); 164 checkConcept<GraphItem<'a'>, Arc>(); 165 { 166 Node n; 167 Arc e(INVALID); 168 n = digraph.source(e); 169 n = digraph.target(e); 170 170 n = digraph.oppositeNode(n, e); 171 } 172 173 174 171 } 172 } 173 174 const _Digraph& digraph; 175 175 }; 176 176 }; 177 177 178 178 /// \brief An empty base undirected graph class. 179 /// 179 /// 180 180 /// This class provides the minimal set of features needed for an 181 181 /// undirected graph structure. All undirected graph concepts have … … 200 200 typedef GraphItem<'u'> Parent; 201 201 /// \brief Default constructor. 202 /// 202 /// 203 203 /// \warning The default constructor is not required to set 204 204 /// the item to some well-defined value. So you should consider it … … 218 218 /// 219 219 /// Besides the core graph item functionality each arc should 220 /// be convertible to the represented edge. 220 /// be convertible to the represented edge. 221 221 Edge(const Arc&) {} 222 222 /// \brief Assign arc to edge. 223 223 /// 224 224 /// Besides the core graph item functionality each arc should 225 /// be convertible to the represented edge. 225 /// be convertible to the represented edge. 226 226 Edge& operator=(const Arc&) { return *this; } 227 227 }; … … 238 238 /// Returns the directed arc from its direction and the 239 239 /// represented edge. 240 Arc direct(const Edge&, bool) const { return INVALID;} 240 Arc direct(const Edge&, bool) const { return INVALID;} 241 241 242 242 /// \brief Returns the directed arc. … … 244 244 /// Returns the directed arc from its source and the 245 245 /// represented edge. 246 Arc direct(const Edge&, const Node&) const { return INVALID;} 246 Arc direct(const Edge&, const Node&) const { return INVALID;} 247 247 248 248 /// \brief Returns the opposite arc. … … 261 261 /// Gives back the other ending of an edge. 262 262 Node v(const Edge&) const { return INVALID;} 263 263 264 264 template <typename _Graph> 265 265 struct Constraints { 266 267 268 269 270 266 typedef typename _Graph::Node Node; 267 typedef typename _Graph::Arc Arc; 268 typedef typename _Graph::Edge Edge; 269 270 void constraints() { 271 271 checkConcept<BaseDigraphComponent, _Graph>(); 272 273 274 275 272 checkConcept<GraphItem<'u'>, Edge>(); 273 { 274 Node n; 275 Edge ue(INVALID); 276 276 Arc e; 277 278 277 n = graph.u(ue); 278 n = graph.v(ue); 279 279 e = graph.direct(ue, true); 280 280 e = graph.direct(ue, n); … … 283 283 bool d = graph.direction(e); 284 284 ignore_unused_variable_warning(d); 285 } 286 287 288 285 } 286 } 287 288 const _Graph& graph; 289 289 }; 290 290 … … 292 292 293 293 /// \brief An empty idable base digraph class. 294 /// 294 /// 295 295 /// This class provides beside the core digraph features 296 296 /// core id functions for the digraph structure. … … 305 305 typedef typename Base::Arc Arc; 306 306 307 /// \brief Gives back an unique integer id for the Node. 308 /// 309 /// Gives back an unique integer id for the Node. 307 /// \brief Gives back an unique integer id for the Node. 308 /// 309 /// Gives back an unique integer id for the Node. 310 310 /// 311 311 int id(const Node&) const { return -1;} … … 315 315 /// Gives back the node by the unique id. 316 316 /// If the digraph does not contain node with the given id 317 /// then the result of the function is undetermined. 317 /// then the result of the function is undetermined. 318 318 Node nodeFromId(int) const { return INVALID;} 319 319 320 /// \brief Gives back an unique integer id for the Arc. 321 /// 322 /// Gives back an unique integer id for the Arc. 320 /// \brief Gives back an unique integer id for the Arc. 321 /// 322 /// Gives back an unique integer id for the Arc. 323 323 /// 324 324 int id(const Arc&) const { return -1;} … … 328 328 /// Gives back the arc by the unique id. 329 329 /// If the digraph does not contain arc with the given id 330 /// then the result of the function is undetermined. 330 /// then the result of the function is undetermined. 331 331 Arc arcFromId(int) const { return INVALID;} 332 332 … … 348 348 struct Constraints { 349 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 350 void constraints() { 351 checkConcept<Base, _Digraph >(); 352 typename _Digraph::Node node; 353 int nid = digraph.id(node); 354 nid = digraph.id(node); 355 node = digraph.nodeFromId(nid); 356 typename _Digraph::Arc arc; 357 int eid = digraph.id(arc); 358 eid = digraph.id(arc); 359 arc = digraph.arcFromId(eid); 360 361 nid = digraph.maxNodeId(); 362 ignore_unused_variable_warning(nid); 363 eid = digraph.maxArcId(); 364 ignore_unused_variable_warning(eid); 365 } 366 367 const _Digraph& digraph; 368 368 }; 369 369 }; 370 370 371 371 /// \brief An empty idable base undirected graph class. 372 /// 372 /// 373 373 /// This class provides beside the core undirected graph features 374 374 /// core id functions for the undirected graph structure. The … … 384 384 using IDableDigraphComponent<_Base>::id; 385 385 386 /// \brief Gives back an unique integer id for the Edge. 387 /// 388 /// Gives back an unique integer id for the Edge. 386 /// \brief Gives back an unique integer id for the Edge. 387 /// 388 /// Gives back an unique integer id for the Edge. 389 389 /// 390 390 int id(const Edge&) const { return -1;} … … 407 407 struct Constraints { 408 408 409 410 411 412 413 414 415 416 417 418 419 420 409 void constraints() { 410 checkConcept<Base, _Graph >(); 411 checkConcept<IDableDigraphComponent<Base>, _Graph >(); 412 typename _Graph::Edge edge; 413 int ueid = graph.id(edge); 414 ueid = graph.id(edge); 415 edge = graph.edgeFromId(ueid); 416 ueid = graph.maxEdgeId(); 417 ignore_unused_variable_warning(ueid); 418 } 419 420 const _Graph& graph; 421 421 }; 422 422 }; … … 451 451 /// \brief Assign operator for items. 452 452 /// 453 /// The items are assignable. 454 /// 455 GraphItemIt& operator=(const GraphItemIt&) { return *this; } 453 /// The items are assignable. 454 /// 455 GraphItemIt& operator=(const GraphItemIt&) { return *this; } 456 456 /// \brief Next item. 457 /// 457 /// 458 458 /// Assign the iterator to the next item. 459 459 /// 460 460 GraphItemIt& operator++() { return *this; } 461 461 /// \brief Equality operator 462 /// 462 /// 463 463 /// Two iterators are equal if and only if they point to the 464 464 /// same object or both are invalid. 465 465 bool operator==(const GraphItemIt&) const { return true;} 466 466 /// \brief Inequality operator 467 /// 467 /// 468 468 /// \sa operator==(Node n) 469 469 /// 470 470 bool operator!=(const GraphItemIt&) const { return true;} 471 471 472 472 template<typename _GraphItemIt> 473 473 struct Constraints { 474 475 _GraphItemIt it1(g); 476 477 478 479 480 481 482 483 484 485 474 void constraints() { 475 _GraphItemIt it1(g); 476 _GraphItemIt it2; 477 478 it2 = ++it1; 479 ++it2 = it1; 480 ++(++it1); 481 482 _Item bi = it1; 483 bi = it2; 484 } 485 _Graph& g; 486 486 }; 487 487 }; … … 490 490 /// 491 491 /// \note Because InArcIt and OutArcIt may not inherit from the same 492 /// base class, the _selector is a additional template parameter. For 493 /// InArcIt you should instantiate it with character 'i' and for 492 /// base class, the _selector is a additional template parameter. For 493 /// InArcIt you should instantiate it with character 'i' and for 494 494 /// OutArcIt with 'o'. 495 495 template <typename _Graph, 496 497 typename _Base = typename _Graph::Node, 498 496 typename _Item = typename _Graph::Arc, 497 typename _Base = typename _Graph::Node, 498 char _selector = '0'> 499 499 class GraphIncIt : public _Item { 500 500 public: … … 509 509 /// 510 510 GraphIncIt(GraphIncIt const& gi) : _Item(gi) {} 511 /// \brief Sets the iterator to the first arc incoming into or outgoing 511 /// \brief Sets the iterator to the first arc incoming into or outgoing 512 512 /// from the node. 513 513 /// 514 /// Sets the iterator to the first arc incoming into or outgoing 514 /// Sets the iterator to the first arc incoming into or outgoing 515 515 /// from the node. 516 516 /// … … 523 523 /// \brief Assign operator for iterators. 524 524 /// 525 /// The iterators are assignable. 526 /// 527 GraphIncIt& operator=(GraphIncIt const&) { return *this; } 525 /// The iterators are assignable. 526 /// 527 GraphIncIt& operator=(GraphIncIt const&) { return *this; } 528 528 /// \brief Next item. 529 529 /// … … 546 546 template <typename _GraphIncIt> 547 547 struct Constraints { 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 548 void constraints() { 549 checkConcept<GraphItem<_selector>, _GraphIncIt>(); 550 _GraphIncIt it1(graph, node); 551 _GraphIncIt it2; 552 553 it2 = ++it1; 554 ++it2 = it1; 555 ++(++it1); 556 _Item e = it1; 557 e = it2; 558 559 } 560 561 _Item arc; 562 _Base node; 563 _Graph graph; 564 _GraphIncIt it; 565 565 }; 566 566 }; … … 576 576 577 577 public: 578 578 579 579 typedef _Base Base; 580 580 typedef typename Base::Node Node; … … 584 584 585 585 /// \name Base iteration 586 /// 586 /// 587 587 /// This interface provides functions for iteration on digraph items 588 588 /// 589 /// @{ 589 /// @{ 590 590 591 591 /// \brief Gives back the first node in the iterating order. 592 /// 592 /// 593 593 /// Gives back the first node in the iterating order. 594 /// 594 /// 595 595 void first(Node&) const {} 596 596 … … 598 598 /// 599 599 /// Gives back the next node in the iterating order. 600 /// 600 /// 601 601 void next(Node&) const {} 602 602 … … 604 604 /// 605 605 /// Gives back the first arc in the iterating order. 606 /// 606 /// 607 607 void first(Arc&) const {} 608 608 … … 610 610 /// 611 611 /// Gives back the next arc in the iterating order. 612 /// 612 /// 613 613 void next(Arc&) const {} 614 614 … … 618 618 /// 619 619 /// Gives back the first of the arcs point to the given node. 620 /// 620 /// 621 621 void firstIn(Arc&, const Node&) const {} 622 622 … … 630 630 /// \brief Gives back the first of the arcs start from the 631 631 /// given node. 632 /// 632 /// 633 633 /// Gives back the first of the arcs start from the given node. 634 /// 634 /// 635 635 void firstOut(Arc&, const Node&) const {} 636 636 … … 639 639 /// 640 640 /// Gives back the next of the arcs start from the given node. 641 /// 641 /// 642 642 void nextOut(Arc&) const {} 643 643 … … 645 645 646 646 /// \name Class based iteration 647 /// 647 /// 648 648 /// This interface provides functions for iteration on digraph items 649 649 /// … … 700 700 /// @} 701 701 702 template <typename _Digraph> 703 struct Constraints { 704 705 702 template <typename _Digraph> 703 struct Constraints { 704 void constraints() { 705 checkConcept<Base, _Digraph>(); 706 706 707 707 { 708 typename _Digraph::Node node(INVALID); 708 typename _Digraph::Node node(INVALID); 709 709 typename _Digraph::Arc arc(INVALID); 710 710 { … … 724 724 digraph.nextOut(arc); 725 725 } 726 } 726 } 727 727 728 728 { … … 731 731 checkConcept<GraphItemIt<_Digraph, typename _Digraph::Node>, 732 732 typename _Digraph::NodeIt >(); 733 checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc, 733 checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc, 734 734 typename _Digraph::Node, 'i'>, typename _Digraph::InArcIt>(); 735 checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc, 735 checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc, 736 736 typename _Digraph::Node, 'o'>, typename _Digraph::OutArcIt>(); 737 737 … … 746 746 } 747 747 } 748 749 750 748 749 const _Digraph& digraph; 750 751 751 }; 752 752 }; … … 766 766 typedef typename Base::Edge Edge; 767 767 768 768 769 769 typedef IterableGraphComponent Graph; 770 770 771 771 /// \name Base iteration 772 /// 772 /// 773 773 /// This interface provides functions for iteration on graph items 774 /// @{ 774 /// @{ 775 775 776 776 using IterableDigraphComponent<_Base>::first; … … 781 781 /// 782 782 /// Gives back the first edge in the iterating order. 783 /// 783 /// 784 784 void first(Edge&) const {} 785 785 … … 788 788 /// 789 789 /// Gives back the next edge in the iterating order. 790 /// 790 /// 791 791 void next(Edge&) const {} 792 792 … … 815 815 816 816 /// \name Class based iteration 817 /// 817 /// 818 818 /// This interface provides functions for iteration on graph items 819 819 /// … … 842 842 /// @} 843 843 844 template <typename _Graph> 845 struct Constraints { 846 847 844 template <typename _Graph> 845 struct Constraints { 846 void constraints() { 847 checkConcept<IterableDigraphComponent<Base>, _Graph>(); 848 848 849 849 { … … 859 859 graph.nextInc(edge, dir); 860 860 } 861 862 } 863 861 862 } 863 864 864 { 865 865 checkConcept<GraphItemIt<_Graph, typename _Graph::Edge>, 866 866 typename _Graph::EdgeIt >(); 867 checkConcept<GraphIncIt<_Graph, typename _Graph::Edge, 867 checkConcept<GraphIncIt<_Graph, typename _Graph::Edge, 868 868 typename _Graph::Node, 'u'>, typename _Graph::IncEdgeIt>(); 869 869 870 870 typename _Graph::Node n; 871 871 typename _Graph::IncEdgeIt ueit(INVALID); … … 874 874 } 875 875 } 876 877 878 876 877 const _Graph& graph; 878 879 879 }; 880 880 }; 881 881 882 882 /// \brief An empty alteration notifier digraph class. 883 /// 883 /// 884 884 /// This class provides beside the core digraph features alteration 885 885 /// notifier interface for the digraph structure. This implements … … 898 898 899 899 /// The node observer registry. 900 typedef AlterationNotifier<AlterableDigraphComponent, Node> 900 typedef AlterationNotifier<AlterableDigraphComponent, Node> 901 901 NodeNotifier; 902 902 /// The arc observer registry. 903 typedef AlterationNotifier<AlterableDigraphComponent, Arc> 903 typedef AlterationNotifier<AlterableDigraphComponent, Arc> 904 904 ArcNotifier; 905 905 906 906 /// \brief Gives back the node alteration notifier. 907 907 /// 908 908 /// Gives back the node alteration notifier. 909 909 NodeNotifier& notifier(Node) const { 910 910 return NodeNotifier(); 911 911 } 912 912 913 913 /// \brief Gives back the arc alteration notifier. 914 914 /// 915 915 /// Gives back the arc alteration notifier. 916 916 ArcNotifier& notifier(Arc) const { 917 917 return ArcNotifier(); 918 918 } 919 919 920 template <typename _Digraph> 921 struct Constraints { 922 923 924 typename _Digraph::NodeNotifier& nn 920 template <typename _Digraph> 921 struct Constraints { 922 void constraints() { 923 checkConcept<Base, _Digraph>(); 924 typename _Digraph::NodeNotifier& nn 925 925 = digraph.notifier(typename _Digraph::Node()); 926 926 927 typename _Digraph::ArcNotifier& en 927 typename _Digraph::ArcNotifier& en 928 928 = digraph.notifier(typename _Digraph::Arc()); 929 929 930 930 ignore_unused_variable_warning(nn); 931 931 ignore_unused_variable_warning(en); 932 933 934 935 936 }; 937 932 } 933 934 const _Digraph& digraph; 935 936 }; 937 938 938 }; 939 939 940 940 /// \brief An empty alteration notifier undirected graph class. 941 /// 941 /// 942 942 /// This class provides beside the core graph features alteration 943 943 /// notifier interface for the graph structure. This implements … … 955 955 956 956 /// The arc observer registry. 957 typedef AlterationNotifier<AlterableGraphComponent, Edge> 957 typedef AlterationNotifier<AlterableGraphComponent, Edge> 958 958 EdgeNotifier; 959 959 960 960 /// \brief Gives back the arc alteration notifier. 961 961 /// 962 962 /// Gives back the arc alteration notifier. 963 963 EdgeNotifier& notifier(Edge) const { 964 964 return EdgeNotifier(); 965 965 } 966 966 967 template <typename _Graph> 968 struct Constraints { 969 970 971 typename _Graph::EdgeNotifier& uen 967 template <typename _Graph> 968 struct Constraints { 969 void constraints() { 970 checkConcept<AlterableGraphComponent<Base>, _Graph>(); 971 typename _Graph::EdgeNotifier& uen 972 972 = graph.notifier(typename _Graph::Edge()); 973 973 ignore_unused_variable_warning(uen); 974 975 976 977 978 }; 979 974 } 975 976 const _Graph& graph; 977 978 }; 979 980 980 }; 981 981 982 982 /// \brief Class describing the concept of graph maps 983 /// 983 /// 984 984 /// This class describes the common interface of the graph maps 985 985 /// (NodeMap, ArcMap), that is \ref maps-page "maps" which can be used to … … 1010 1010 /// Copy Constructor. 1011 1011 GraphMap(const GraphMap&) : Parent() {} 1012 1012 1013 1013 /// \brief Assign operator. 1014 1014 /// 1015 1015 /// Assign operator. It does not mofify the underlying graph, 1016 1016 /// it just iterates on the current item set and set the map 1017 /// with the value returned by the assigned map. 1017 /// with the value returned by the assigned map. 1018 1018 template <typename CMap> 1019 GraphMap& operator=(const CMap&) { 1019 GraphMap& operator=(const CMap&) { 1020 1020 checkConcept<ReadMap<Key, Value>, CMap>(); 1021 1021 return *this; … … 1024 1024 template<typename _Map> 1025 1025 struct Constraints { 1026 1027 1028 1029 1030 1031 1032 1033 1034 1026 void constraints() { 1027 checkConcept<ReadWriteMap<Key, Value>, _Map >(); 1028 // Construction with a graph parameter 1029 _Map a(g); 1030 // Constructor with a graph and a default value parameter 1031 _Map a2(g,t); 1032 // Copy constructor. 1033 _Map b(c); 1034 1035 1035 ReadMap<Key, Value> cmap; 1036 1036 b = cmap; 1037 1037 1038 1039 1040 1041 1042 1043 1044 1038 ignore_unused_variable_warning(a2); 1039 ignore_unused_variable_warning(b); 1040 } 1041 1042 const _Map &c; 1043 const Graph &g; 1044 const typename GraphMap::Value &t; 1045 1045 }; 1046 1046 … … 1071 1071 typedef GraphMap<MappableDigraphComponent, Node, _Value> Parent; 1072 1072 1073 1074 1075 1076 explicit NodeMap(const MappableDigraphComponent& digraph) 1073 /// \brief Construct a new map. 1074 /// 1075 /// Construct a new map for the digraph. 1076 explicit NodeMap(const MappableDigraphComponent& digraph) 1077 1077 : Parent(digraph) {} 1078 1078 1079 1080 1081 1082 1079 /// \brief Construct a new map with default value. 1080 /// 1081 /// Construct a new map for the digraph and initalise the values. 1082 NodeMap(const MappableDigraphComponent& digraph, const _Value& value) 1083 1083 : Parent(digraph, value) {} 1084 1084 1085 1086 1087 1088 1089 1090 1091 1092 1085 /// \brief Copy constructor. 1086 /// 1087 /// Copy Constructor. 1088 NodeMap(const NodeMap& nm) : Parent(nm) {} 1089 1090 /// \brief Assign operator. 1091 /// 1092 /// Assign operator. 1093 1093 template <typename CMap> 1094 NodeMap& operator=(const CMap&) { 1094 NodeMap& operator=(const CMap&) { 1095 1095 checkConcept<ReadMap<Node, _Value>, CMap>(); 1096 1096 return *this; … … 1108 1108 typedef GraphMap<MappableDigraphComponent, Arc, _Value> Parent; 1109 1109 1110 1111 1112 1113 explicit ArcMap(const MappableDigraphComponent& digraph) 1110 /// \brief Construct a new map. 1111 /// 1112 /// Construct a new map for the digraph. 1113 explicit ArcMap(const MappableDigraphComponent& digraph) 1114 1114 : Parent(digraph) {} 1115 1115 1116 1117 1118 1119 1116 /// \brief Construct a new map with default value. 1117 /// 1118 /// Construct a new map for the digraph and initalise the values. 1119 ArcMap(const MappableDigraphComponent& digraph, const _Value& value) 1120 1120 : Parent(digraph, value) {} 1121 1121 1122 1123 1124 1125 1126 1127 1128 1129 1122 /// \brief Copy constructor. 1123 /// 1124 /// Copy Constructor. 1125 ArcMap(const ArcMap& nm) : Parent(nm) {} 1126 1127 /// \brief Assign operator. 1128 /// 1129 /// Assign operator. 1130 1130 template <typename CMap> 1131 ArcMap& operator=(const CMap&) { 1131 ArcMap& operator=(const CMap&) { 1132 1132 checkConcept<ReadMap<Arc, _Value>, CMap>(); 1133 1133 return *this; … … 1140 1140 struct Constraints { 1141 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 checkConcept<GraphMap<_Digraph, typename _Digraph::Node, int>, 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 } 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, Dummy>, 1175 1176 } 1177 1178 1179 1142 struct Dummy { 1143 int value; 1144 Dummy() : value(0) {} 1145 Dummy(int _v) : value(_v) {} 1146 }; 1147 1148 void constraints() { 1149 checkConcept<Base, _Digraph>(); 1150 { // int map test 1151 typedef typename _Digraph::template NodeMap<int> IntNodeMap; 1152 checkConcept<GraphMap<_Digraph, typename _Digraph::Node, int>, 1153 IntNodeMap >(); 1154 } { // bool map test 1155 typedef typename _Digraph::template NodeMap<bool> BoolNodeMap; 1156 checkConcept<GraphMap<_Digraph, typename _Digraph::Node, bool>, 1157 BoolNodeMap >(); 1158 } { // Dummy map test 1159 typedef typename _Digraph::template NodeMap<Dummy> DummyNodeMap; 1160 checkConcept<GraphMap<_Digraph, typename _Digraph::Node, Dummy>, 1161 DummyNodeMap >(); 1162 } 1163 1164 { // int map test 1165 typedef typename _Digraph::template ArcMap<int> IntArcMap; 1166 checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, int>, 1167 IntArcMap >(); 1168 } { // bool map test 1169 typedef typename _Digraph::template ArcMap<bool> BoolArcMap; 1170 checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, bool>, 1171 BoolArcMap >(); 1172 } { // Dummy map test 1173 typedef typename _Digraph::template ArcMap<Dummy> DummyArcMap; 1174 checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, Dummy>, 1175 DummyArcMap >(); 1176 } 1177 } 1178 1179 _Digraph& digraph; 1180 1180 }; 1181 1181 }; … … 1200 1200 /// 1201 1201 template <typename _Value> 1202 class EdgeMap : public GraphMap<Graph, Edge, _Value> { 1202 class EdgeMap : public GraphMap<Graph, Edge, _Value> { 1203 1203 public: 1204 1204 typedef GraphMap<MappableGraphComponent, Edge, _Value> Parent; 1205 1205 1206 1207 1208 1209 explicit EdgeMap(const MappableGraphComponent& graph) 1206 /// \brief Construct a new map. 1207 /// 1208 /// Construct a new map for the graph. 1209 explicit EdgeMap(const MappableGraphComponent& graph) 1210 1210 : Parent(graph) {} 1211 1211 1212 1213 1214 1215 1212 /// \brief Construct a new map with default value. 1213 /// 1214 /// Construct a new map for the graph and initalise the values. 1215 EdgeMap(const MappableGraphComponent& graph, const _Value& value) 1216 1216 : Parent(graph, value) {} 1217 1217 1218 1219 1220 1221 1222 1223 1224 1225 1218 /// \brief Copy constructor. 1219 /// 1220 /// Copy Constructor. 1221 EdgeMap(const EdgeMap& nm) : Parent(nm) {} 1222 1223 /// \brief Assign operator. 1224 /// 1225 /// Assign operator. 1226 1226 template <typename CMap> 1227 EdgeMap& operator=(const CMap&) { 1227 EdgeMap& operator=(const CMap&) { 1228 1228 checkConcept<ReadMap<Edge, _Value>, CMap>(); 1229 1229 return *this; … … 1236 1236 struct Constraints { 1237 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 checkConcept<GraphMap<_Graph, typename _Graph::Edge, Dummy>, 1258 1259 } 1260 1261 1262 1238 struct Dummy { 1239 int value; 1240 Dummy() : value(0) {} 1241 Dummy(int _v) : value(_v) {} 1242 }; 1243 1244 void constraints() { 1245 checkConcept<MappableGraphComponent<Base>, _Graph>(); 1246 1247 { // int map test 1248 typedef typename _Graph::template EdgeMap<int> IntEdgeMap; 1249 checkConcept<GraphMap<_Graph, typename _Graph::Edge, int>, 1250 IntEdgeMap >(); 1251 } { // bool map test 1252 typedef typename _Graph::template EdgeMap<bool> BoolEdgeMap; 1253 checkConcept<GraphMap<_Graph, typename _Graph::Edge, bool>, 1254 BoolEdgeMap >(); 1255 } { // Dummy map test 1256 typedef typename _Graph::template EdgeMap<Dummy> DummyEdgeMap; 1257 checkConcept<GraphMap<_Graph, typename _Graph::Edge, Dummy>, 1258 DummyEdgeMap >(); 1259 } 1260 } 1261 1262 _Graph& graph; 1263 1263 }; 1264 1264 }; … … 1283 1283 /// 1284 1284 Node addNode() { 1285 1285 return INVALID; 1286 1286 } 1287 1287 1288 1288 /// \brief Adds a new arc connects the given two nodes. 1289 1289 /// 1290 1290 /// Adds a new arc connects the the given two nodes. 1291 1291 Arc addArc(const Node&, const Node&) { 1292 1292 return INVALID; 1293 1293 } 1294 1294 1295 1295 template <typename _Digraph> 1296 1296 struct Constraints { 1297 1297 void constraints() { 1298 1298 checkConcept<Base, _Digraph>(); 1299 1300 1301 1302 1303 1304 1305 1306 1299 typename _Digraph::Node node_a, node_b; 1300 node_a = digraph.addNode(); 1301 node_b = digraph.addNode(); 1302 typename _Digraph::Arc arc; 1303 arc = digraph.addArc(node_a, node_b); 1304 } 1305 1306 _Digraph& digraph; 1307 1307 }; 1308 1308 }; … … 1328 1328 /// 1329 1329 Node addNode() { 1330 1330 return INVALID; 1331 1331 } 1332 1332 1333 1333 /// \brief Adds a new arc connects the given two nodes. 1334 1334 /// 1335 1335 /// Adds a new arc connects the the given two nodes. 1336 1336 Edge addArc(const Node&, const Node&) { 1337 1337 return INVALID; 1338 1338 } 1339 1339 1340 1340 template <typename _Graph> 1341 1341 struct Constraints { 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1342 void constraints() { 1343 checkConcept<Base, _Graph>(); 1344 typename _Graph::Node node_a, node_b; 1345 node_a = graph.addNode(); 1346 node_b = graph.addNode(); 1347 typename _Graph::Edge edge; 1348 edge = graph.addEdge(node_a, node_b); 1349 } 1350 1351 _Graph& graph; 1352 1352 }; 1353 1353 }; 1354 1354 1355 1355 /// \brief An empty erasable digraph class. 1356 /// 1356 /// 1357 1357 /// This class provides beside the core digraph features core erase 1358 1358 /// functions for the digraph structure. The main difference between … … 1369 1369 /// \brief Erase a node from the digraph. 1370 1370 /// 1371 /// Erase a node from the digraph. This function should 1371 /// Erase a node from the digraph. This function should 1372 1372 /// erase all arcs connecting to the node. 1373 void erase(const Node&) {} 1373 void erase(const Node&) {} 1374 1374 1375 1375 /// \brief Erase an arc from the digraph. … … 1381 1381 template <typename _Digraph> 1382 1382 struct Constraints { 1383 1383 void constraints() { 1384 1384 checkConcept<Base, _Digraph>(); 1385 1386 1387 1388 1389 1390 1391 1385 typename _Digraph::Node node; 1386 digraph.erase(node); 1387 typename _Digraph::Arc arc; 1388 digraph.erase(arc); 1389 } 1390 1391 _Digraph& digraph; 1392 1392 }; 1393 1393 }; 1394 1394 1395 1395 /// \brief An empty erasable base undirected graph class. 1396 /// 1396 /// 1397 1397 /// This class provides beside the core undirected graph features 1398 1398 /// core erase functions for the undirceted graph structure. The … … 1411 1411 /// Erase a node from the graph. This function should erase 1412 1412 /// arcs connecting to the node. 1413 void erase(const Node&) {} 1413 void erase(const Node&) {} 1414 1414 1415 1415 /// \brief Erase an arc from the graph. … … 1421 1421 template <typename _Graph> 1422 1422 struct Constraints { 1423 1423 void constraints() { 1424 1424 checkConcept<Base, _Graph>(); 1425 1426 1427 1428 1429 1430 1431 1425 typename _Graph::Node node; 1426 graph.erase(node); 1427 typename _Graph::Edge edge; 1428 graph.erase(edge); 1429 } 1430 1431 _Graph& graph; 1432 1432 }; 1433 1433 }; … … 1449 1449 /// Erase all nodes and arcs from the digraph. 1450 1450 /// 1451 void clear() {} 1451 void clear() {} 1452 1452 1453 1453 template <typename _Digraph> 1454 1454 struct Constraints { 1455 1455 void constraints() { 1456 1456 checkConcept<Base, _Digraph>(); 1457 1458 1459 1460 1457 digraph.clear(); 1458 } 1459 1460 _Digraph digraph; 1461 1461 }; 1462 1462 }; … … 1476 1476 template <typename _Graph> 1477 1477 struct Constraints { 1478 1478 void constraints() { 1479 1479 checkConcept<ClearableGraphComponent<Base>, _Graph>(); 1480 1481 1482 1480 } 1481 1482 _Graph graph; 1483 1483 }; 1484 1484 }; -
lemon/concepts/heap.h
r203 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 53 53 /// the user. 54 54 /// 55 /// The \c ItemIntMap must be initialized in such a way, that it 55 /// The \c ItemIntMap must be initialized in such a way, that it 56 56 /// assigns \c PRE_HEAP (<tt>-1</tt>) to every item. 57 57 enum State { 58 59 60 58 IN_HEAP = 0, 59 PRE_HEAP = -1, 60 POST_HEAP = -2 61 61 }; 62 62 63 63 /// \brief The constructor. 64 64 /// … … 86 86 87 87 /// \brief Inserts an item into the heap with the given priority. 88 /// 89 /// Inserts the given item into the heap with the given priority. 88 /// 89 /// Inserts the given item into the heap with the given priority. 90 90 /// \param i The item to insert. 91 91 /// \param p The priority of the item. … … 113 113 /// 114 114 /// Removes the given item from the heap if it is already stored. 115 /// \param i The item to delete. 115 /// \param i The item to delete. 116 116 void erase(const Item &i) {} 117 117 118 118 /// \brief The priority of an item. 119 119 /// 120 /// Returns the priority of the given item. 120 /// Returns the priority of the given item. 121 121 /// \pre \c i must be in the heap. 122 122 /// \param i The item. … … 134 134 /// \param p The priority. 135 135 void set(const Item &i, const Prio &p) {} 136 136 137 137 /// \brief Decreases the priority of an item to the given value. 138 138 /// … … 175 175 struct Constraints { 176 176 public: 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 177 void constraints() { 178 typedef typename _Heap::Item OwnItem; 179 typedef typename _Heap::Prio OwnPrio; 180 typedef typename _Heap::State OwnState; 181 182 Item item; 183 Prio prio; 184 item=Item(); 185 prio=Prio(); 186 ignore_unused_variable_warning(item); 187 ignore_unused_variable_warning(prio); 188 189 OwnItem own_item; 190 OwnPrio own_prio; 191 OwnState own_state; 192 own_item=Item(); 193 own_prio=Prio(); 194 ignore_unused_variable_warning(own_item); 195 ignore_unused_variable_warning(own_prio); 196 ignore_unused_variable_warning(own_state); 197 198 _Heap heap1(map); 199 _Heap heap2 = heap1; 200 ignore_unused_variable_warning(heap1); 201 ignore_unused_variable_warning(heap2); 202 203 int s = heap.size(); 204 ignore_unused_variable_warning(s); 205 bool e = heap.empty(); 206 ignore_unused_variable_warning(e); 207 208 prio = heap.prio(); 209 item = heap.top(); 210 prio = heap[item]; 211 own_prio = heap.prio(); 212 own_item = heap.top(); 213 own_prio = heap[own_item]; 214 215 heap.push(item, prio); 216 heap.push(own_item, own_prio); 217 heap.pop(); 218 219 heap.set(item, prio); 220 heap.decrease(item, prio); 221 heap.increase(item, prio); 222 heap.set(own_item, own_prio); 223 heap.decrease(own_item, own_prio); 224 heap.increase(own_item, own_prio); 225 226 heap.erase(item); 227 heap.erase(own_item); 228 heap.clear(); 229 230 own_state = heap.state(own_item); 231 heap.state(own_item, own_state); 232 233 own_state = _Heap::PRE_HEAP; 234 own_state = _Heap::IN_HEAP; 235 own_state = _Heap::POST_HEAP; 236 } 237 238 _Heap& heap; 239 ItemIntMap& map; 240 240 }; 241 241 }; -
lemon/concepts/maps.h
r114 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 48 48 49 49 /// Returns the value associated with the given key. 50 Value operator[](const Key &) const { 50 Value operator[](const Key &) const { 51 51 return *static_cast<Value *>(0); 52 52 } … … 54 54 template<typename _ReadMap> 55 55 struct Constraints { 56 57 58 59 60 61 62 63 64 65 66 67 68 69 56 void constraints() { 57 Value val = m[key]; 58 val = m[key]; 59 typename _ReadMap::Value own_val = m[own_key]; 60 own_val = m[own_key]; 61 62 ignore_unused_variable_warning(key); 63 ignore_unused_variable_warning(val); 64 ignore_unused_variable_warning(own_key); 65 ignore_unused_variable_warning(own_val); 66 } 67 const Key& key; 68 const typename _ReadMap::Key& own_key; 69 const _ReadMap& m; 70 70 }; 71 71 … … 94 94 template <typename _WriteMap> 95 95 struct Constraints { 96 97 98 99 100 101 102 103 104 105 106 107 108 109 96 void constraints() { 97 m.set(key, val); 98 m.set(own_key, own_val); 99 100 ignore_unused_variable_warning(key); 101 ignore_unused_variable_warning(val); 102 ignore_unused_variable_warning(own_key); 103 ignore_unused_variable_warning(own_val); 104 } 105 const Key& key; 106 const Value& val; 107 const typename _WriteMap::Key& own_key; 108 const typename _WriteMap::Value& own_val; 109 _WriteMap& m; 110 110 }; 111 111 }; … … 117 117 template<typename K, typename T> 118 118 class ReadWriteMap : public ReadMap<K,T>, 119 119 public WriteMap<K,T> 120 120 { 121 121 public: … … 126 126 127 127 /// Returns the value associated with the given key. 128 Value operator[](const Key &) const { 128 Value operator[](const Key &) const { 129 129 return *static_cast<Value *>(0); 130 130 } … … 135 135 template<typename _ReadWriteMap> 136 136 struct Constraints { 137 138 139 140 137 void constraints() { 138 checkConcept<ReadMap<K, T>, _ReadWriteMap >(); 139 checkConcept<WriteMap<K, T>, _ReadWriteMap >(); 140 } 141 141 }; 142 142 }; … … 165 165 166 166 /// Returns a reference to the value associated with the given key. 167 Reference operator[](const Key &) { 167 Reference operator[](const Key &) { 168 168 return *static_cast<Value *>(0); 169 169 } … … 179 179 template<typename _ReferenceMap> 180 180 struct Constraints { 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 181 void constraints() { 182 checkConcept<ReadWriteMap<K, T>, _ReferenceMap >(); 183 ref = m[key]; 184 m[key] = val; 185 m[key] = ref; 186 m[key] = cref; 187 own_ref = m[own_key]; 188 m[own_key] = own_val; 189 m[own_key] = own_ref; 190 m[own_key] = own_cref; 191 m[key] = m[own_key]; 192 m[own_key] = m[key]; 193 } 194 const Key& key; 195 Value& val; 196 Reference ref; 197 ConstReference cref; 198 const typename _ReferenceMap::Key& own_key; 199 typename _ReferenceMap::Value& own_val; 200 typename _ReferenceMap::Reference own_ref; 201 typename _ReferenceMap::ConstReference own_cref; 202 _ReferenceMap& m; 203 203 }; 204 204 }; -
lemon/concepts/path.h
r157 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 40 40 /// 41 41 /// A skeleton structure for representing directed paths in a 42 /// digraph. 42 /// digraph. 43 43 /// \tparam _Digraph The digraph type in which the path is. 44 44 /// … … 84 84 class ArcIt { 85 85 public: 86 87 88 89 90 91 86 /// Default constructor 87 ArcIt() {} 88 /// Invalid constructor 89 ArcIt(Invalid) {} 90 /// Constructor for first arc 91 ArcIt(const Path &) {} 92 92 93 93 /// Conversion to Arc 94 95 96 97 98 99 100 101 102 103 104 94 operator Arc() const { return INVALID; } 95 96 /// Next arc 97 ArcIt& operator++() {return *this;} 98 99 /// Comparison operator 100 bool operator==(const ArcIt&) const {return true;} 101 /// Comparison operator 102 bool operator!=(const ArcIt&) const {return true;} 103 /// Comparison operator 104 bool operator<(const ArcIt&) const {return false;} 105 105 106 106 }; … … 138 138 139 139 namespace _path_bits { 140 140 141 141 template <typename _Digraph, typename _Path, typename RevPathTag = void> 142 142 struct PathDumperConstraints { … … 163 163 template <typename _Digraph, typename _Path> 164 164 struct PathDumperConstraints< 165 _Digraph, _Path, 165 _Digraph, _Path, 166 166 typename enable_if<typename _Path::RevPathTag, void>::type 167 167 > { … … 185 185 _Path& p; 186 186 }; 187 187 188 188 } 189 189 … … 210 210 /// The paths can be constructed from any path type by a 211 211 /// template constructor or a template assignment operator. 212 /// 212 /// 213 213 template <typename _Digraph> 214 214 class PathDumper { … … 239 239 class ArcIt { 240 240 public: 241 242 243 244 245 246 241 /// Default constructor 242 ArcIt() {} 243 /// Invalid constructor 244 ArcIt(Invalid) {} 245 /// Constructor for first arc 246 ArcIt(const PathDumper&) {} 247 247 248 248 /// Conversion to Arc 249 250 251 252 253 254 255 256 257 258 259 249 operator Arc() const { return INVALID; } 250 251 /// Next arc 252 ArcIt& operator++() {return *this;} 253 254 /// Comparison operator 255 bool operator==(const ArcIt&) const {return true;} 256 /// Comparison operator 257 bool operator!=(const ArcIt&) const {return true;} 258 /// Comparison operator 259 bool operator<(const ArcIt&) const {return false;} 260 260 261 261 }; … … 267 267 class RevArcIt { 268 268 public: 269 270 271 272 273 274 269 /// Default constructor 270 RevArcIt() {} 271 /// Invalid constructor 272 RevArcIt(Invalid) {} 273 /// Constructor for first arc 274 RevArcIt(const PathDumper &) {} 275 275 276 276 /// Conversion to Arc 277 278 279 280 281 282 283 284 285 286 287 277 operator Arc() const { return INVALID; } 278 279 /// Next arc 280 RevArcIt& operator++() {return *this;} 281 282 /// Comparison operator 283 bool operator==(const RevArcIt&) const {return true;} 284 /// Comparison operator 285 bool operator!=(const RevArcIt&) const {return true;} 286 /// Comparison operator 287 bool operator<(const RevArcIt&) const {return false;} 288 288 289 289 }; -
lemon/counter.h
r168 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 27 27 ///\brief Tools for counting steps and events 28 28 29 namespace lemon 29 namespace lemon 30 30 { 31 31 … … 33 33 34 34 template<class P> 35 class _SubCounter 35 class _SubCounter 36 36 { 37 37 P &_parent; … … 50 50 _SubCounter(P &parent,const char *title,std::ostream &os=std::cerr) 51 51 : _parent(parent), _title(title), _os(os), count(0) {} 52 ~_SubCounter() { 52 ~_SubCounter() { 53 53 _os << _title << count <<std::endl; 54 54 _parent+=count; … … 64 64 65 65 template<class P> 66 class _NoSubCounter 66 class _NoSubCounter 67 67 { 68 68 P &_parent; … … 70 70 typedef _NoSubCounter<_NoSubCounter<P> > SubCounter; 71 71 typedef _NoSubCounter<_NoSubCounter<P> > NoSubCounter; 72 72 73 73 _NoSubCounter(P &parent) :_parent(parent) {} 74 _NoSubCounter(P &parent,std::string,std::ostream &) 75 :_parent(parent) {} 76 _NoSubCounter(P &parent,std::string) 74 _NoSubCounter(P &parent,std::string,std::ostream &) 75 :_parent(parent) {} 76 _NoSubCounter(P &parent,std::string) 77 77 :_parent(parent) {} 78 78 _NoSubCounter(P &parent,const char *,std::ostream &) … … 103 103 /// for different types of operations. 104 104 /// A report containing the given title and the value of the counter 105 /// is automatically printed on destruction. 105 /// is automatically printed on destruction. 106 106 /// 107 107 /// The following example shows the usage of counters and subcounters. … … 134 134 /// 135 135 /// \sa NoCounter 136 class Counter 136 class Counter 137 137 { 138 138 std::string _title; … … 142 142 143 143 /// SubCounter class 144 144 145 145 /// This class can be used to setup subcounters for a \ref Counter 146 146 /// to have finer reports. A subcounter provides exactly the same … … 148 148 /// decrements the value of its parent. 149 149 /// Subcounters can also have subcounters. 150 /// 150 /// 151 151 /// The parent counter must be given as the first parameter of the 152 152 /// constructor. Apart from that a title and an \c ostream object … … 157 157 /// would like to turn off this report, use \ref NoSubCounter 158 158 /// instead. 159 /// 159 /// 160 160 /// \sa NoSubCounter 161 161 typedef _SubCounter<Counter> SubCounter; 162 162 163 /// SubCounter class without printing report on destruction 164 163 /// SubCounter class without printing report on destruction 164 165 165 /// This class can be used to setup subcounters for a \ref Counter. 166 166 /// It is the same as \ref SubCounter but it does not print report … … 169 169 /// 170 170 /// Replacing \ref SubCounter "SubCounter"s with \ref NoSubCounter 171 /// "NoSubCounter"s makes it possible to turn off reporting 171 /// "NoSubCounter"s makes it possible to turn off reporting 172 172 /// subcounter values without actually removing the definitions 173 173 /// and the increment or decrement operators. … … 179 179 Counter() : _title(), _os(std::cerr), count(0) {} 180 180 /// Constructor. 181 Counter(std::string title,std::ostream &os=std::cerr) 181 Counter(std::string title,std::ostream &os=std::cerr) 182 182 : _title(title), _os(os), count(0) {} 183 183 /// Constructor. … … 205 205 /// \note This function does not reset the values of 206 206 /// \ref SubCounter "SubCounter"s but it resets \ref NoSubCounter 207 /// "NoSubCounter"s along with the main counter. 207 /// "NoSubCounter"s along with the main counter. 208 208 void reset(int c=0) {count=c;} 209 209 /// Returns the value of the counter. -
lemon/dfs.h
r158 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 35 35 namespace lemon { 36 36 37 37 38 38 ///Default traits class of Dfs class. 39 39 … … 43 43 struct DfsDefaultTraits 44 44 { 45 ///The digraph type the algorithm runs on. 45 ///The digraph type the algorithm runs on. 46 46 typedef GR Digraph; 47 47 ///\brief The type of the map that stores the last 48 48 ///arcs of the %DFS paths. 49 /// 49 /// 50 50 ///The type of the map that stores the last 51 51 ///arcs of the %DFS paths. … … 54 54 typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap; 55 55 ///Instantiates a PredMap. 56 57 ///This function instantiates a \ref PredMap. 56 57 ///This function instantiates a \ref PredMap. 58 58 ///\param G is the digraph, to which we would like to define the PredMap. 59 59 ///\todo The digraph alone may be insufficient to initialize 60 static PredMap *createPredMap(const GR &G) 60 static PredMap *createPredMap(const GR &G) 61 61 { 62 62 return new PredMap(G); … … 64 64 65 65 ///The type of the map that indicates which nodes are processed. 66 66 67 67 ///The type of the map that indicates which nodes are processed. 68 68 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 70 70 typedef NullMap<typename Digraph::Node,bool> ProcessedMap; 71 71 ///Instantiates a ProcessedMap. 72 73 ///This function instantiates a \ref ProcessedMap. 72 73 ///This function instantiates a \ref ProcessedMap. 74 74 ///\param g is the digraph, to which 75 75 ///we would like to define the \ref ProcessedMap … … 83 83 } 84 84 ///The type of the map that indicates which nodes are reached. 85 85 86 86 ///The type of the map that indicates which nodes are reached. 87 87 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 89 89 typedef typename Digraph::template NodeMap<bool> ReachedMap; 90 90 ///Instantiates a ReachedMap. 91 92 ///This function instantiates a \ref ReachedMap. 91 92 ///This function instantiates a \ref ReachedMap. 93 93 ///\param G is the digraph, to which 94 94 ///we would like to define the \ref ReachedMap. … … 98 98 } 99 99 ///The type of the map that stores the dists of the nodes. 100 100 101 101 ///The type of the map that stores the dists of the nodes. 102 102 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 104 104 typedef typename Digraph::template NodeMap<int> DistMap; 105 105 ///Instantiates a DistMap. 106 107 ///This function instantiates a \ref DistMap. 106 107 ///This function instantiates a \ref DistMap. 108 108 ///\param G is the digraph, to which we would like to define the \ref DistMap 109 109 static DistMap *createDistMap(const GR &G) … … 112 112 } 113 113 }; 114 114 115 115 ///%DFS algorithm class. 116 116 117 117 ///\ingroup search 118 118 ///This class provides an efficient implementation of the %DFS algorithm. … … 128 128 #ifdef DOXYGEN 129 129 template <typename GR, 130 130 typename TR> 131 131 #else 132 132 template <typename GR=ListDigraph, 133 133 typename TR=DfsDefaultTraits<GR> > 134 134 #endif 135 135 class Dfs { … … 144 144 public: 145 145 virtual const char* what() const throw() { 146 146 return "lemon::Dfs::UninitializedParameter"; 147 147 } 148 148 }; … … 159 159 ///\e 160 160 typedef typename Digraph::OutArcIt OutArcIt; 161 161 162 162 ///\brief The type of the map that stores the last 163 163 ///arcs of the %DFS paths. … … 193 193 194 194 ///Creates the maps if necessary. 195 195 196 196 ///\todo Better memory allocation (instead of new). 197 void create_maps() 197 void create_maps() 198 198 { 199 199 if(!_pred) { 200 201 200 local_pred = true; 201 _pred = Traits::createPredMap(*G); 202 202 } 203 203 if(!_dist) { 204 205 204 local_dist = true; 205 _dist = Traits::createDistMap(*G); 206 206 } 207 207 if(!_reached) { 208 209 208 local_reached = true; 209 _reached = Traits::createReachedMap(*G); 210 210 } 211 211 if(!_processed) { 212 213 212 local_processed = true; 213 _processed = Traits::createProcessedMap(*G); 214 214 } 215 215 } … … 218 218 219 219 Dfs() {} 220 220 221 221 public: 222 222 … … 230 230 struct DefPredMapTraits : public Traits { 231 231 typedef T PredMap; 232 static PredMap *createPredMap(const Digraph &G) 232 static PredMap *createPredMap(const Digraph &G) 233 233 { 234 234 throw UninitializedParameter(); 235 235 } 236 236 }; … … 244 244 typedef Dfs<Digraph, DefPredMapTraits<T> > Create; 245 245 }; 246 247 246 247 248 248 template <class T> 249 249 struct DefDistMapTraits : public Traits { 250 250 typedef T DistMap; 251 static DistMap *createDistMap(const Digraph &) 251 static DistMap *createDistMap(const Digraph &) 252 252 { 253 253 throw UninitializedParameter(); 254 254 } 255 255 }; … … 263 263 typedef Dfs<Digraph, DefDistMapTraits<T> > Create; 264 264 }; 265 265 266 266 template <class T> 267 267 struct DefReachedMapTraits : public Traits { 268 268 typedef T ReachedMap; 269 static ReachedMap *createReachedMap(const Digraph &) 269 static ReachedMap *createReachedMap(const Digraph &) 270 270 { 271 271 throw UninitializedParameter(); 272 272 } 273 273 }; … … 285 285 struct DefProcessedMapTraits : public Traits { 286 286 typedef T ProcessedMap; 287 static ProcessedMap *createProcessedMap(const Digraph &) 287 static ProcessedMap *createProcessedMap(const Digraph &) 288 288 { 289 289 throw UninitializedParameter(); 290 290 } 291 291 }; … … 296 296 /// 297 297 template <class T> 298 struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > { 298 struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > { 299 299 typedef Dfs< Digraph, DefProcessedMapTraits<T> > Create; 300 300 }; 301 301 302 302 struct DefDigraphProcessedMapTraits : public Traits { 303 303 typedef typename Digraph::template NodeMap<bool> ProcessedMap; 304 static ProcessedMap *createProcessedMap(const Digraph &G) 304 static ProcessedMap *createProcessedMap(const Digraph &G) 305 305 { 306 306 return new ProcessedMap(G); 307 307 } 308 308 }; … … 315 315 template <class T> 316 316 class DefProcessedMapToBeDefaultMap : 317 public Dfs< Digraph, DefDigraphProcessedMapTraits> { 317 public Dfs< Digraph, DefDigraphProcessedMapTraits> { 318 318 typedef Dfs< Digraph, DefDigraphProcessedMapTraits> Create; 319 319 }; 320 320 321 321 ///@} 322 322 323 public: 324 323 public: 324 325 325 ///Constructor. 326 326 327 327 ///\param _G the digraph the algorithm will run on. 328 328 /// … … 334 334 _processed(NULL), local_processed(false) 335 335 { } 336 336 337 337 ///Destructor. 338 ~Dfs() 338 ~Dfs() 339 339 { 340 340 if(local_pred) delete _pred; … … 351 351 ///automatically allocated map, of course. 352 352 ///\return <tt> (*this) </tt> 353 Dfs &predMap(PredMap &m) 353 Dfs &predMap(PredMap &m) 354 354 { 355 355 if(local_pred) { 356 357 356 delete _pred; 357 local_pred=false; 358 358 } 359 359 _pred = &m; … … 368 368 ///automatically allocated map, of course. 369 369 ///\return <tt> (*this) </tt> 370 Dfs &distMap(DistMap &m) 370 Dfs &distMap(DistMap &m) 371 371 { 372 372 if(local_dist) { 373 374 373 delete _dist; 374 local_dist=false; 375 375 } 376 376 _dist = &m; … … 385 385 ///automatically allocated map, of course. 386 386 ///\return <tt> (*this) </tt> 387 Dfs &reachedMap(ReachedMap &m) 387 Dfs &reachedMap(ReachedMap &m) 388 388 { 389 389 if(local_reached) { 390 391 390 delete _reached; 391 local_reached=false; 392 392 } 393 393 _reached = &m; … … 402 402 ///automatically allocated map, of course. 403 403 ///\return <tt> (*this) </tt> 404 Dfs &processedMap(ProcessedMap &m) 404 Dfs &processedMap(ProcessedMap &m) 405 405 { 406 406 if(local_processed) { 407 408 407 delete _processed; 408 local_processed=false; 409 409 } 410 410 _processed = &m; … … 435 435 _stack_head=-1; 436 436 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) { 437 438 439 440 441 } 442 } 443 437 _pred->set(u,INVALID); 438 // _predNode->set(u,INVALID); 439 _reached->set(u,false); 440 _processed->set(u,false); 441 } 442 } 443 444 444 ///Adds a new source node. 445 445 … … 451 451 { 452 452 if(!(*_reached)[s]) 453 454 455 456 457 458 459 460 461 462 463 464 465 466 } 467 453 { 454 _reached->set(s,true); 455 _pred->set(s,INVALID); 456 OutArcIt e(*G,s); 457 if(e!=INVALID) { 458 _stack[++_stack_head]=e; 459 _dist->set(s,_stack_head); 460 } 461 else { 462 _processed->set(s,true); 463 _dist->set(s,0); 464 } 465 } 466 } 467 468 468 ///Processes the next arc. 469 469 … … 474 474 ///\pre The stack must not be empty! 475 475 Arc processNextArc() 476 { 476 { 477 477 Node m; 478 478 Arc e=_stack[_stack_head]; 479 479 if(!(*_reached)[m=G->target(e)]) { 480 481 482 483 484 480 _pred->set(m,e); 481 _reached->set(m,true); 482 ++_stack_head; 483 _stack[_stack_head] = OutArcIt(*G, m); 484 _dist->set(m,_stack_head); 485 485 } 486 486 else { 487 488 487 m=G->source(e); 488 ++_stack[_stack_head]; 489 489 } 490 490 while(_stack_head>=0 && _stack[_stack_head]==INVALID) { 491 492 493 494 495 496 491 _processed->set(m,true); 492 --_stack_head; 493 if(_stack_head>=0) { 494 m=G->source(_stack[_stack_head]); 495 ++_stack[_stack_head]; 496 } 497 497 } 498 498 return e; … … 505 505 /// empty. 506 506 OutArcIt nextArc() 507 { 507 { 508 508 return _stack_head>=0?_stack[_stack_head]:INVALID; 509 509 } … … 516 516 bool emptyQueue() { return _stack_head<0; } 517 517 ///Returns the number of the nodes to be processed. 518 518 519 519 ///Returns the number of the nodes to be processed in the queue. 520 520 int queueSize() { return _stack_head+1; } 521 521 522 522 ///Executes the algorithm. 523 523 … … 538 538 while ( !emptyQueue() ) processNextArc(); 539 539 } 540 540 541 541 ///Executes the algorithm until \c dest is reached. 542 542 … … 555 555 void start(Node dest) 556 556 { 557 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest ) 558 559 } 560 557 while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest ) 558 processNextArc(); 559 } 560 561 561 ///Executes the algorithm until a condition is met. 562 562 … … 583 583 584 584 ///Runs %DFS algorithm to visit all nodes in the digraph. 585 585 586 586 ///This method runs the %DFS algorithm in order to 587 587 ///compute the … … 611 611 612 612 ///Runs %DFS algorithm from node \c s. 613 613 614 614 ///This method runs the %DFS algorithm from a root node \c s 615 615 ///in order to … … 630 630 start(); 631 631 } 632 632 633 633 ///Finds the %DFS path between \c s and \c t. 634 634 635 635 ///Finds the %DFS path between \c s and \c t. 636 636 /// … … 650 650 return reached(t)?_stack_head+1:0; 651 651 } 652 652 653 653 ///@} 654 654 … … 658 658 ///Before the use of these functions, 659 659 ///either run() or start() must be called. 660 660 661 661 ///@{ 662 662 … … 664 664 665 665 ///Gives back the shortest path. 666 666 667 667 ///Gives back the shortest path. 668 668 ///\pre The \c t should be reachable from the source. 669 Path path(Node t) 669 Path path(Node t) 670 670 { 671 671 return Path(*G, *_pred, t); … … 676 676 ///Returns the distance of a node from the root(s). 677 677 ///\pre \ref run() must be called before using this function. 678 ///\warning If node \c v is unreachable from the root(s) then the return 678 ///\warning If node \c v is unreachable from the root(s) then the return 679 679 ///value of this funcion is undefined. 680 680 int dist(Node v) const { return (*_dist)[v]; } … … 706 706 ///using this function. 707 707 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID: 708 709 708 G->source((*_pred)[v]); } 709 710 710 ///Returns a reference to the NodeMap of distances. 711 711 … … 714 714 ///be called before using this function. 715 715 const DistMap &distMap() const { return *_dist;} 716 716 717 717 ///Returns a reference to the %DFS arc-tree map. 718 718 … … 722 722 ///must be called before using this function. 723 723 const PredMap &predMap() const { return *_pred;} 724 724 725 725 ///Checks if a node is reachable from the root. 726 726 … … 731 731 /// 732 732 bool reached(Node v) { return (*_reached)[v]; } 733 733 734 734 ///@} 735 735 }; … … 742 742 struct DfsWizardDefaultTraits 743 743 { 744 ///The digraph type the algorithm runs on. 744 ///The digraph type the algorithm runs on. 745 745 typedef GR Digraph; 746 746 ///\brief The type of the map that stores the last 747 747 ///arcs of the %DFS paths. 748 /// 748 /// 749 749 ///The type of the map that stores the last 750 750 ///arcs of the %DFS paths. … … 753 753 typedef NullMap<typename Digraph::Node,typename GR::Arc> PredMap; 754 754 ///Instantiates a PredMap. 755 756 ///This function instantiates a \ref PredMap. 755 756 ///This function instantiates a \ref PredMap. 757 757 ///\param g is the digraph, to which we would like to define the PredMap. 758 758 ///\todo The digraph alone may be insufficient to initialize 759 759 #ifdef DOXYGEN 760 static PredMap *createPredMap(const GR &g) 760 static PredMap *createPredMap(const GR &g) 761 761 #else 762 static PredMap *createPredMap(const GR &) 762 static PredMap *createPredMap(const GR &) 763 763 #endif 764 764 { … … 767 767 768 768 ///The type of the map that indicates which nodes are processed. 769 769 770 770 ///The type of the map that indicates which nodes are processed. 771 771 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 773 773 typedef NullMap<typename Digraph::Node,bool> ProcessedMap; 774 774 ///Instantiates a ProcessedMap. 775 776 ///This function instantiates a \ref ProcessedMap. 775 776 ///This function instantiates a \ref ProcessedMap. 777 777 ///\param g is the digraph, to which 778 778 ///we would like to define the \ref ProcessedMap … … 786 786 } 787 787 ///The type of the map that indicates which nodes are reached. 788 788 789 789 ///The type of the map that indicates which nodes are reached. 790 790 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 792 792 typedef typename Digraph::template NodeMap<bool> ReachedMap; 793 793 ///Instantiates a ReachedMap. 794 795 ///This function instantiates a \ref ReachedMap. 794 795 ///This function instantiates a \ref ReachedMap. 796 796 ///\param G is the digraph, to which 797 797 ///we would like to define the \ref ReachedMap. … … 801 801 } 802 802 ///The type of the map that stores the dists of the nodes. 803 803 804 804 ///The type of the map that stores the dists of the nodes. 805 805 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 807 807 typedef NullMap<typename Digraph::Node,int> DistMap; 808 808 ///Instantiates a DistMap. 809 810 ///This function instantiates a \ref DistMap. 809 810 ///This function instantiates a \ref DistMap. 811 811 ///\param g is the digraph, to which we would like to define the \ref DistMap 812 812 #ifdef DOXYGEN … … 819 819 } 820 820 }; 821 821 822 822 /// Default traits used by \ref DfsWizard 823 823 … … 849 849 ///Pointer to the source node. 850 850 Node _source; 851 851 852 852 public: 853 853 /// Constructor. 854 854 855 855 /// This constructor does not require parameters, therefore it initiates 856 856 /// all of the attributes to default values (0, INVALID). 857 857 DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0), 858 858 _dist(0), _source(INVALID) {} 859 859 860 860 /// Constructor. 861 861 862 862 /// This constructor requires some parameters, 863 863 /// listed in the parameters list. … … 866 866 /// \param s is the initial value of \ref _source 867 867 DfsWizardBase(const GR &g, Node s=INVALID) : 868 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))), 868 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))), 869 869 _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {} 870 870 871 871 }; 872 872 873 873 /// A class to make the usage of the Dfs algorithm easier 874 874 … … 905 905 //\e 906 906 typedef typename Digraph::OutArcIt OutArcIt; 907 907 908 908 ///\brief The type of the map that stores 909 909 ///the reached nodes … … 935 935 936 936 ///Runs Dfs algorithm from a given node. 937 937 938 938 ///Runs Dfs algorithm from a given node. 939 939 ///The node can be given by the \ref source function. … … 942 942 if(Base::_source==INVALID) throw UninitializedParameter(); 943 943 Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g)); 944 if(Base::_reached) 944 if(Base::_reached) 945 945 alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached)); 946 if(Base::_processed) 946 if(Base::_processed) 947 947 alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); 948 if(Base::_pred) 948 if(Base::_pred) 949 949 alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); 950 if(Base::_dist) 950 if(Base::_dist) 951 951 alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); 952 952 alg.run(Base::_source); … … 969 969 DefPredMapBase(const TR &b) : TR(b) {} 970 970 }; 971 971 972 972 ///\brief \ref named-templ-param "Named parameter" 973 973 ///function for setting PredMap type … … 977 977 /// 978 978 template<class T> 979 DfsWizard<DefPredMapBase<T> > predMap(const T &t) 979 DfsWizard<DefPredMapBase<T> > predMap(const T &t) 980 980 { 981 981 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); 982 982 return DfsWizard<DefPredMapBase<T> >(*this); 983 983 } 984 985 984 985 986 986 template<class T> 987 987 struct DefReachedMapBase : public Base { … … 990 990 DefReachedMapBase(const TR &b) : TR(b) {} 991 991 }; 992 992 993 993 ///\brief \ref named-templ-param "Named parameter" 994 994 ///function for setting ReachedMap … … 998 998 /// 999 999 template<class T> 1000 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t) 1000 DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t) 1001 1001 { 1002 1002 Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t)); 1003 1003 return DfsWizard<DefReachedMapBase<T> >(*this); 1004 1004 } 1005 1005 1006 1006 1007 1007 template<class T> … … 1011 1011 DefProcessedMapBase(const TR &b) : TR(b) {} 1012 1012 }; 1013 1013 1014 1014 ///\brief \ref named-templ-param "Named parameter" 1015 1015 ///function for setting ProcessedMap … … 1019 1019 /// 1020 1020 template<class T> 1021 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t) 1021 DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t) 1022 1022 { 1023 1023 Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t)); 1024 1024 return DfsWizard<DefProcessedMapBase<T> >(*this); 1025 1025 } 1026 1026 1027 1027 template<class T> 1028 1028 struct DefDistMapBase : public Base { … … 1031 1031 DefDistMapBase(const TR &b) : TR(b) {} 1032 1032 }; 1033 1033 1034 1034 ///\brief \ref named-templ-param "Named parameter" 1035 1035 ///function for setting DistMap type … … 1039 1039 /// 1040 1040 template<class T> 1041 DfsWizard<DefDistMapBase<T> > distMap(const T &t) 1041 DfsWizard<DefDistMapBase<T> > distMap(const T &t) 1042 1042 { 1043 1043 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); 1044 1044 return DfsWizard<DefDistMapBase<T> >(*this); 1045 1045 } 1046 1046 1047 1047 /// Sets the source node, from which the Dfs algorithm runs. 1048 1048 1049 1049 /// Sets the source node, from which the Dfs algorithm runs. 1050 1050 /// \param s is the source node. 1051 DfsWizard<TR> &source(Node s) 1051 DfsWizard<TR> &source(Node s) 1052 1052 { 1053 1053 Base::_source=s; 1054 1054 return *this; 1055 1055 } 1056 1056 1057 1057 }; 1058 1058 1059 1059 ///Function type interface for Dfs algorithm. 1060 1060 … … 1083 1083 #ifdef DOXYGEN 1084 1084 /// \brief Visitor class for dfs. 1085 /// 1086 /// It gives a simple interface for a functional interface for dfs 1087 /// traversal. The traversal on a linear data structure. 1085 /// 1086 /// It gives a simple interface for a functional interface for dfs 1087 /// traversal. The traversal on a linear data structure. 1088 1088 template <typename _Digraph> 1089 1089 struct DfsVisitor { … … 1092 1092 typedef typename Digraph::Node Node; 1093 1093 /// \brief Called when the arc reach a node. 1094 /// 1094 /// 1095 1095 /// It is called when the dfs find an arc which target is not 1096 1096 /// reached yet. 1097 1097 void discover(const Arc& arc) {} 1098 1098 /// \brief Called when the node reached first time. 1099 /// 1099 /// 1100 1100 /// It is Called when the node reached first time. 1101 1101 void reach(const Node& node) {} 1102 1102 /// \brief Called when we step back on an arc. 1103 /// 1103 /// 1104 1104 /// It is called when the dfs should step back on the arc. 1105 1105 void backtrack(const Arc& arc) {} 1106 1106 /// \brief Called when we step back from the node. 1107 /// 1107 /// 1108 1108 /// It is called when we step back from the node. 1109 1109 void leave(const Node& node) {} 1110 /// \brief Called when the arc examined but target of the arc 1110 /// \brief Called when the arc examined but target of the arc 1111 1111 /// already discovered. 1112 /// 1113 /// It called when the arc examined but the target of the arc 1112 /// 1113 /// It called when the arc examined but the target of the arc 1114 1114 /// already discovered. 1115 1115 void examine(const Arc& arc) {} 1116 1116 /// \brief Called for the source node of the dfs. 1117 /// 1117 /// 1118 1118 /// It is called for the source node of the dfs. 1119 1119 void start(const Node& node) {} 1120 1120 /// \brief Called when we leave the source node of the dfs. 1121 /// 1121 /// 1122 1122 /// It is called when we leave the source node of the dfs. 1123 1123 void stop(const Node& node) {} … … 1141 1141 struct Constraints { 1142 1142 void constraints() { 1143 1144 1145 1146 1147 1148 1149 1150 1151 1143 Arc arc; 1144 Node node; 1145 visitor.discover(arc); 1146 visitor.reach(node); 1147 visitor.backtrack(arc); 1148 visitor.leave(node); 1149 visitor.examine(arc); 1150 visitor.start(node); 1151 visitor.stop(arc); 1152 1152 } 1153 1153 _Visitor& visitor; … … 1163 1163 struct DfsVisitDefaultTraits { 1164 1164 1165 /// \brief The digraph type the algorithm runs on. 1165 /// \brief The digraph type the algorithm runs on. 1166 1166 typedef _Digraph Digraph; 1167 1167 1168 1168 /// \brief The type of the map that indicates which nodes are reached. 1169 /// 1169 /// 1170 1170 /// The type of the map that indicates which nodes are reached. 1171 1171 /// It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 1175 1175 /// \brief Instantiates a ReachedMap. 1176 1176 /// 1177 /// This function instantiates a \ref ReachedMap. 1177 /// This function instantiates a \ref ReachedMap. 1178 1178 /// \param digraph is the digraph, to which 1179 1179 /// we would like to define the \ref ReachedMap. … … 1183 1183 1184 1184 }; 1185 1185 1186 1186 /// %DFS Visit algorithm class. 1187 1187 1188 1188 /// \ingroup search 1189 1189 /// This class provides an efficient implementation of the %DFS algorithm … … 1192 1192 /// The %DfsVisit class provides an alternative interface to the Dfs 1193 1193 /// class. It works with callback mechanism, the DfsVisit object calls 1194 /// on every dfs event the \c Visitor class member functions. 1194 /// on every dfs event the \c Visitor class member functions. 1195 1195 /// 1196 1196 /// \tparam _Digraph The digraph type the algorithm runs on. The default value is 1197 1197 /// \ref ListDigraph. The value of _Digraph is not used directly by Dfs, it 1198 1198 /// is only passed to \ref DfsDefaultTraits. 1199 /// \tparam _Visitor The Visitor object for the algorithm. The 1199 /// \tparam _Visitor The Visitor object for the algorithm. The 1200 1200 /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty Visitor which 1201 1201 /// does not observe the Dfs events. If you want to observe the dfs 1202 1202 /// events you should implement your own Visitor class. 1203 /// \tparam _Traits Traits class to set various data types used by the 1203 /// \tparam _Traits Traits class to set various data types used by the 1204 1204 /// algorithm. The default traits class is 1205 1205 /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>". … … 1212 1212 #else 1213 1213 template <typename _Digraph = ListDigraph, 1214 1215 1214 typename _Visitor = DfsVisitor<_Digraph>, 1215 typename _Traits = DfsDefaultTraits<_Digraph> > 1216 1216 #endif 1217 1217 class DfsVisit { 1218 1218 public: 1219 1219 1220 1220 /// \brief \ref Exception for uninitialized parameters. 1221 1221 /// … … 1224 1224 class UninitializedParameter : public lemon::UninitializedParameter { 1225 1225 public: 1226 virtual const char* what() const throw() 1226 virtual const char* what() const throw() 1227 1227 { 1228 1228 return "lemon::DfsVisit::UninitializedParameter"; 1229 1229 } 1230 1230 }; … … 1263 1263 void create_maps() { 1264 1264 if(!_reached) { 1265 1266 1265 local_reached = true; 1266 _reached = Traits::createReachedMap(*_digraph); 1267 1267 } 1268 1268 } … … 1271 1271 1272 1272 DfsVisit() {} 1273 1273 1274 1274 public: 1275 1275 … … 1283 1283 typedef T ReachedMap; 1284 1284 static ReachedMap *createReachedMap(const Digraph &digraph) { 1285 1286 } 1287 }; 1288 /// \brief \ref named-templ-param "Named parameter" for setting 1285 throw UninitializedParameter(); 1286 } 1287 }; 1288 /// \brief \ref named-templ-param "Named parameter" for setting 1289 1289 /// ReachedMap type 1290 1290 /// … … 1292 1292 template <class T> 1293 1293 struct DefReachedMap : public DfsVisit< Digraph, Visitor, 1294 1294 DefReachedMapTraits<T> > { 1295 1295 typedef DfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create; 1296 1296 }; 1297 1297 ///@} 1298 1298 1299 public: 1300 1299 public: 1300 1301 1301 /// \brief Constructor. 1302 1302 /// … … 1306 1306 /// \param visitor The visitor of the algorithm. 1307 1307 /// 1308 DfsVisit(const Digraph& digraph, Visitor& visitor) 1308 DfsVisit(const Digraph& digraph, Visitor& visitor) 1309 1309 : _digraph(&digraph), _visitor(&visitor), 1310 1311 1310 _reached(0), local_reached(false) {} 1311 1312 1312 /// \brief Destructor. 1313 1313 /// … … 1326 1326 DfsVisit &reachedMap(ReachedMap &m) { 1327 1327 if(local_reached) { 1328 1329 1328 delete _reached; 1329 local_reached=false; 1330 1330 } 1331 1331 _reached = &m; … … 1354 1354 _stack_head = -1; 1355 1355 for (NodeIt u(*_digraph) ; u != INVALID ; ++u) { 1356 1357 } 1358 } 1359 1356 _reached->set(u, false); 1357 } 1358 } 1359 1360 1360 /// \brief Adds a new source node. 1361 1361 /// … … 1363 1363 void addSource(Node s) { 1364 1364 if(!(*_reached)[s]) { 1365 1366 1367 1368 Arc e; 1369 1370 1371 1372 1373 1374 1375 1376 } 1377 1365 _reached->set(s,true); 1366 _visitor->start(s); 1367 _visitor->reach(s); 1368 Arc e; 1369 _digraph->firstOut(e, s); 1370 if (e != INVALID) { 1371 _stack[++_stack_head] = e; 1372 } else { 1373 _visitor->leave(s); 1374 } 1375 } 1376 } 1377 1378 1378 /// \brief Processes the next arc. 1379 1379 /// … … 1383 1383 /// 1384 1384 /// \pre The stack must not be empty! 1385 Arc processNextArc() { 1385 Arc processNextArc() { 1386 1386 Arc e = _stack[_stack_head]; 1387 1387 Node m = _digraph->target(e); 1388 1388 if(!(*_reached)[m]) { 1389 1390 1391 1392 1389 _visitor->discover(e); 1390 _visitor->reach(m); 1391 _reached->set(m, true); 1392 _digraph->firstOut(_stack[++_stack_head], m); 1393 1393 } else { 1394 1395 1396 1394 _visitor->examine(e); 1395 m = _digraph->source(e); 1396 _digraph->nextOut(_stack[_stack_head]); 1397 1397 } 1398 1398 while (_stack_head>=0 && _stack[_stack_head] == INVALID) { 1399 1400 1401 1402 1403 1404 1405 1406 _visitor->stop(m); 1407 1399 _visitor->leave(m); 1400 --_stack_head; 1401 if (_stack_head >= 0) { 1402 _visitor->backtrack(_stack[_stack_head]); 1403 m = _digraph->source(_stack[_stack_head]); 1404 _digraph->nextOut(_stack[_stack_head]); 1405 } else { 1406 _visitor->stop(m); 1407 } 1408 1408 } 1409 1409 return e; … … 1416 1416 /// \return The next arc to be processed or INVALID if the stack is 1417 1417 /// empty. 1418 Arc nextArc() { 1418 Arc nextArc() { 1419 1419 return _stack_head >= 0 ? _stack[_stack_head] : INVALID; 1420 1420 } … … 1431 1431 /// Returns the number of the nodes to be processed in the queue. 1432 1432 int queueSize() { return _stack_head + 1; } 1433 1433 1434 1434 /// \brief Executes the algorithm. 1435 1435 /// … … 1441 1441 while ( !emptyQueue() ) processNextArc(); 1442 1442 } 1443 1443 1444 1444 /// \brief Executes the algorithm until \c dest is reached. 1445 1445 /// … … 1449 1449 /// with addSource() before using this function. 1450 1450 void start(Node dest) { 1451 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest ) 1452 1453 } 1454 1451 while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest ) 1452 processNextArc(); 1453 } 1454 1455 1455 /// \brief Executes the algorithm until a condition is met. 1456 1456 /// … … 1491 1491 1492 1492 /// \brief Runs %DFSVisit algorithm to visit all nodes in the digraph. 1493 1493 1494 1494 /// This method runs the %DFS algorithm in order to 1495 1495 /// compute the %DFS path to each node. The algorithm computes -
lemon/dijkstra.h
r184 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 35 35 36 36 /// \brief Default OperationTraits for the Dijkstra algorithm class. 37 /// 37 /// 38 38 /// It defines all computational operations and constants which are 39 39 /// used in the Dijkstra algorithm. … … 55 55 56 56 /// \brief Widest path OperationTraits for the Dijkstra algorithm class. 57 /// 57 /// 58 58 /// It defines all computational operations and constants which are 59 59 /// used in the Dijkstra algorithm for widest path computation. … … 73 73 } 74 74 }; 75 75 76 76 ///Default traits class of Dijkstra class. 77 77 … … 82 82 struct DijkstraDefaultTraits 83 83 { 84 ///The digraph type the algorithm runs on. 84 ///The digraph type the algorithm runs on. 85 85 typedef GR Digraph; 86 86 ///The type of the map that stores the arc lengths. … … 104 104 ///Instantiates a HeapCrossRef. 105 105 106 ///This function instantiates a \c HeapCrossRef. 107 /// \param G is the digraph, to which we would like to define the 106 ///This function instantiates a \c HeapCrossRef. 107 /// \param G is the digraph, to which we would like to define the 108 108 /// HeapCrossRef. 109 static HeapCrossRef *createHeapCrossRef(const GR &G) 109 static HeapCrossRef *createHeapCrossRef(const GR &G) 110 110 { 111 111 return new HeapCrossRef(G); 112 112 } 113 113 114 114 ///The heap type used by Dijkstra algorithm. 115 115 … … 120 120 typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap; 121 121 122 static Heap *createHeap(HeapCrossRef& R) 122 static Heap *createHeap(HeapCrossRef& R) 123 123 { 124 124 return new Heap(R); … … 127 127 ///\brief The type of the map that stores the last 128 128 ///arcs of the shortest paths. 129 /// 129 /// 130 130 ///The type of the map that stores the last 131 131 ///arcs of the shortest paths. … … 134 134 typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap; 135 135 ///Instantiates a PredMap. 136 137 ///This function instantiates a \c PredMap. 136 137 ///This function instantiates a \c PredMap. 138 138 ///\param G is the digraph, to which we would like to define the PredMap. 139 139 ///\todo The digraph alone may be insufficient for the initialization 140 static PredMap *createPredMap(const GR &G) 140 static PredMap *createPredMap(const GR &G) 141 141 { 142 142 return new PredMap(G); … … 144 144 145 145 ///The type of the map that stores whether a nodes is processed. 146 146 147 147 ///The type of the map that stores whether a nodes is processed. 148 148 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 153 153 typedef NullMap<typename Digraph::Node,bool> ProcessedMap; 154 154 ///Instantiates a ProcessedMap. 155 156 ///This function instantiates a \c ProcessedMap. 155 156 ///This function instantiates a \c ProcessedMap. 157 157 ///\param g is the digraph, to which 158 158 ///we would like to define the \c ProcessedMap … … 166 166 } 167 167 ///The type of the map that stores the dists of the nodes. 168 168 169 169 ///The type of the map that stores the dists of the nodes. 170 170 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 172 172 typedef typename Digraph::template NodeMap<typename LM::Value> DistMap; 173 173 ///Instantiates a DistMap. 174 175 ///This function instantiates a \ref DistMap. 174 175 ///This function instantiates a \ref DistMap. 176 176 ///\param G is the digraph, to which we would like to define the \ref DistMap 177 177 static DistMap *createDistMap(const GR &G) … … 180 180 } 181 181 }; 182 182 183 183 ///%Dijkstra algorithm class. 184 184 185 185 /// \ingroup shortest_path 186 186 ///This class provides an efficient implementation of %Dijkstra algorithm. … … 203 203 ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>". The value 204 204 ///of LM is not used directly by Dijkstra, it is only passed to \ref 205 ///DijkstraDefaultTraits. 205 ///DijkstraDefaultTraits. 206 206 ///\tparam TR Traits class to set 207 207 ///various data types used by the algorithm. The default traits … … 215 215 #else 216 216 template <typename GR=ListDigraph, 217 218 217 typename LM=typename GR::template ArcMap<int>, 218 typename TR=DijkstraDefaultTraits<GR,LM> > 219 219 #endif 220 220 class Dijkstra { … … 229 229 public: 230 230 virtual const char* what() const throw() { 231 231 return "lemon::Dijkstra::UninitializedParameter"; 232 232 } 233 233 }; … … 244 244 ///\e 245 245 typedef typename Digraph::OutArcIt OutArcIt; 246 246 247 247 ///The type of the length of the arcs. 248 248 typedef typename TR::LengthMap::Value Value; … … 289 289 290 290 ///Creates the maps if necessary. 291 291 292 292 ///\todo Better memory allocation (instead of new). 293 void create_maps() 293 void create_maps() 294 294 { 295 295 if(!_pred) { 296 297 296 local_pred = true; 297 _pred = Traits::createPredMap(*G); 298 298 } 299 299 if(!_dist) { 300 301 300 local_dist = true; 301 _dist = Traits::createDistMap(*G); 302 302 } 303 303 if(!_processed) { 304 305 304 local_processed = true; 305 _processed = Traits::createProcessedMap(*G); 306 306 } 307 307 if (!_heap_cross_ref) { 308 309 308 local_heap_cross_ref = true; 309 _heap_cross_ref = Traits::createHeapCrossRef(*G); 310 310 } 311 311 if (!_heap) { 312 313 314 } 315 } 316 312 local_heap = true; 313 _heap = Traits::createHeap(*_heap_cross_ref); 314 } 315 } 316 317 317 public : 318 318 319 319 typedef Dijkstra Create; 320 320 321 321 ///\name Named template parameters 322 322 … … 328 328 static PredMap *createPredMap(const Digraph &) 329 329 { 330 330 throw UninitializedParameter(); 331 331 } 332 332 }; … … 336 336 /// 337 337 template <class T> 338 struct DefPredMap 339 : public Dijkstra< Digraph, 340 typedef Dijkstra< Digraph, 341 }; 342 338 struct DefPredMap 339 : public Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > { 340 typedef Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > Create; 341 }; 342 343 343 template <class T> 344 344 struct DefDistMapTraits : public Traits { … … 346 346 static DistMap *createDistMap(const Digraph &) 347 347 { 348 348 throw UninitializedParameter(); 349 349 } 350 350 }; … … 354 354 /// 355 355 template <class T> 356 struct DefDistMap 357 : public Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > { 356 struct DefDistMap 357 : public Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > { 358 358 typedef Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > Create; 359 359 }; 360 360 361 361 template <class T> 362 362 struct DefProcessedMapTraits : public Traits { 363 363 typedef T ProcessedMap; 364 static ProcessedMap *createProcessedMap(const Digraph &G) 364 static ProcessedMap *createProcessedMap(const Digraph &G) 365 365 { 366 366 throw UninitializedParameter(); 367 367 } 368 368 }; … … 372 372 /// 373 373 template <class T> 374 struct DefProcessedMap 375 : public Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > {376 typedef Dijkstra< Digraph, 377 }; 378 374 struct DefProcessedMap 375 : public Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > { 376 typedef Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > Create; 377 }; 378 379 379 struct DefDigraphProcessedMapTraits : public Traits { 380 380 typedef typename Digraph::template NodeMap<bool> ProcessedMap; 381 static ProcessedMap *createProcessedMap(const Digraph &G) 381 static ProcessedMap *createProcessedMap(const Digraph &G) 382 382 { 383 383 return new ProcessedMap(G); 384 384 } 385 385 }; … … 391 391 ///If you don't set it explicitely, it will be automatically allocated. 392 392 template <class T> 393 struct DefProcessedMapToBeDefaultMap 393 struct DefProcessedMapToBeDefaultMap 394 394 : public Dijkstra< Digraph, LengthMap, DefDigraphProcessedMapTraits> { 395 395 typedef Dijkstra< Digraph, LengthMap, DefDigraphProcessedMapTraits> Create; … … 401 401 typedef H Heap; 402 402 static HeapCrossRef *createHeapCrossRef(const Digraph &) { 403 404 } 405 static Heap *createHeap(HeapCrossRef &) 403 throw UninitializedParameter(); 404 } 405 static Heap *createHeap(HeapCrossRef &) 406 406 { 407 407 throw UninitializedParameter(); 408 408 } 409 409 }; … … 411 411 ///heap and cross reference type 412 412 /// 413 ///\ref named-templ-param "Named parameter" for setting heap and cross 413 ///\ref named-templ-param "Named parameter" for setting heap and cross 414 414 ///reference type 415 415 /// 416 416 template <class H, class CR = typename Digraph::template NodeMap<int> > 417 417 struct DefHeap 418 : public Dijkstra< Digraph, LengthMap, DefHeapTraits<H, CR> > {419 typedef Dijkstra< Digraph, 418 : public Dijkstra< Digraph, LengthMap, DefHeapTraits<H, CR> > { 419 typedef Dijkstra< Digraph, LengthMap, DefHeapTraits<H, CR> > Create; 420 420 }; 421 421 … … 425 425 typedef H Heap; 426 426 static HeapCrossRef *createHeapCrossRef(const Digraph &G) { 427 428 } 429 static Heap *createHeap(HeapCrossRef &R) 427 return new HeapCrossRef(G); 428 } 429 static Heap *createHeap(HeapCrossRef &R) 430 430 { 431 431 return new Heap(R); 432 432 } 433 433 }; … … 435 435 ///heap and cross reference type with automatic allocation 436 436 /// 437 ///\ref named-templ-param "Named parameter" for setting heap and cross 438 ///reference type. It can allocate the heap and the cross reference 439 ///object if the cross reference's constructor waits for the digraph as 437 ///\ref named-templ-param "Named parameter" for setting heap and cross 438 ///reference type. It can allocate the heap and the cross reference 439 ///object if the cross reference's constructor waits for the digraph as 440 440 ///parameter and the heap's constructor waits for the cross reference. 441 441 template <class H, class CR = typename Digraph::template NodeMap<int> > 442 442 struct DefStandardHeap 443 : public Dijkstra< Digraph, LengthMap, DefStandardHeapTraits<H, CR> > {444 typedef Dijkstra< Digraph, LengthMap, DefStandardHeapTraits<H, CR> >443 : public Dijkstra< Digraph, LengthMap, DefStandardHeapTraits<H, CR> > { 444 typedef Dijkstra< Digraph, LengthMap, DefStandardHeapTraits<H, CR> > 445 445 Create; 446 446 }; … … 450 450 typedef T OperationTraits; 451 451 }; 452 453 /// \brief \ref named-templ-param "Named parameter" for setting 452 453 /// \brief \ref named-templ-param "Named parameter" for setting 454 454 /// OperationTraits type 455 455 /// … … 462 462 Create; 463 463 }; 464 464 465 465 ///@} 466 466 … … 470 470 Dijkstra() {} 471 471 472 public: 473 472 public: 473 474 474 ///Constructor. 475 475 476 476 ///\param _G the digraph the algorithm will run on. 477 477 ///\param _length the length map used by the algorithm. … … 484 484 _heap(NULL), local_heap(false) 485 485 { } 486 486 487 487 ///Destructor. 488 ~Dijkstra() 488 ~Dijkstra() 489 489 { 490 490 if(local_pred) delete _pred; … … 499 499 ///Sets the length map. 500 500 ///\return <tt> (*this) </tt> 501 Dijkstra &lengthMap(const LengthMap &m) 501 Dijkstra &lengthMap(const LengthMap &m) 502 502 { 503 503 length = &m; … … 512 512 ///automatically allocated map, of course. 513 513 ///\return <tt> (*this) </tt> 514 Dijkstra &predMap(PredMap &m) 514 Dijkstra &predMap(PredMap &m) 515 515 { 516 516 if(local_pred) { 517 518 517 delete _pred; 518 local_pred=false; 519 519 } 520 520 _pred = &m; … … 529 529 ///automatically allocated map, of course. 530 530 ///\return <tt> (*this) </tt> 531 Dijkstra &distMap(DistMap &m) 531 Dijkstra &distMap(DistMap &m) 532 532 { 533 533 if(local_dist) { 534 535 534 delete _dist; 535 local_dist=false; 536 536 } 537 537 _dist = &m; … … 549 549 { 550 550 if(local_heap_cross_ref) { 551 552 551 delete _heap_cross_ref; 552 local_heap_cross_ref=false; 553 553 } 554 554 _heap_cross_ref = &cr; 555 555 if(local_heap) { 556 557 556 delete _heap; 557 local_heap=false; 558 558 } 559 559 _heap = &hp; … … 593 593 _heap->clear(); 594 594 for ( NodeIt u(*G) ; u!=INVALID ; ++u ) { 595 596 597 598 } 599 } 600 595 _pred->set(u,INVALID); 596 _processed->set(u,false); 597 _heap_cross_ref->set(u,Heap::PRE_HEAP); 598 } 599 } 600 601 601 ///Adds a new source node. 602 602 … … 611 611 { 612 612 if(_heap->state(s) != Heap::IN_HEAP) { 613 613 _heap->push(s,dst); 614 614 } else if(OperationTraits::less((*_heap)[s], dst)) { 615 616 617 } 618 } 619 615 _heap->set(s,dst); 616 _pred->set(s,INVALID); 617 } 618 } 619 620 620 ///Processes the next node in the priority heap 621 621 … … 627 627 Node processNextNode() 628 628 { 629 Node v=_heap->top(); 629 Node v=_heap->top(); 630 630 Value oldvalue=_heap->prio(); 631 631 _heap->pop(); 632 632 finalizeNodeData(v,oldvalue); 633 633 634 634 for(OutArcIt e(*G,v); e!=INVALID; ++e) { 635 Node w=G->target(e); 636 637 638 _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e])); 639 640 641 642 643 644 645 _heap->decrease(w, newvalue); 646 647 648 649 650 651 652 635 Node w=G->target(e); 636 switch(_heap->state(w)) { 637 case Heap::PRE_HEAP: 638 _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e])); 639 _pred->set(w,e); 640 break; 641 case Heap::IN_HEAP: 642 { 643 Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]); 644 if ( OperationTraits::less(newvalue, (*_heap)[w]) ) { 645 _heap->decrease(w, newvalue); 646 _pred->set(w,e); 647 } 648 } 649 break; 650 case Heap::POST_HEAP: 651 break; 652 } 653 653 } 654 654 return v; … … 656 656 657 657 ///Next node to be processed. 658 658 659 659 ///Next node to be processed. 660 660 /// … … 662 662 /// is empty. 663 663 Node nextNode() 664 { 664 { 665 665 return !_heap->empty()?_heap->top():INVALID; 666 666 } 667 667 668 668 ///\brief Returns \c false if there are nodes 669 669 ///to be processed in the priority heap … … 677 677 /// 678 678 int queueSize() { return _heap->size(); } 679 679 680 680 ///Executes the algorithm. 681 681 … … 696 696 while ( !_heap->empty() ) processNextNode(); 697 697 } 698 698 699 699 ///Executes the algorithm until \c dest is reached. 700 700 … … 716 716 if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio()); 717 717 } 718 718 719 719 ///Executes the algorithm until a condition is met. 720 720 … … 737 737 return _heap->top(); 738 738 } 739 739 740 740 ///Runs %Dijkstra algorithm from node \c s. 741 741 742 742 ///This method runs the %Dijkstra algorithm from a root node \c s 743 743 ///in order to … … 758 758 start(); 759 759 } 760 760 761 761 ///Finds the shortest path between \c s and \c t. 762 762 763 763 ///Finds the shortest path between \c s and \c t. 764 764 /// … … 778 778 return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t]; 779 779 } 780 780 781 781 ///@} 782 782 … … 786 786 ///Before the use of these functions, 787 787 ///either run() or start() must be called. 788 788 789 789 ///@{ 790 790 791 791 ///Gives back the shortest path. 792 792 793 793 ///Gives back the shortest path. 794 794 ///\pre The \c t should be reachable from the source. 795 Path path(Node t) 795 Path path(Node t) 796 796 { 797 797 return Path(*G, *_pred, t); … … 833 833 ///using this function. 834 834 Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID: 835 836 835 G->source((*_pred)[v]); } 836 837 837 ///Returns a reference to the NodeMap of distances. 838 838 … … 840 840 ///be called before using this function. 841 841 const DistMap &distMap() const { return *_dist;} 842 842 843 843 ///Returns a reference to the shortest path tree map. 844 844 … … 847 847 ///\pre \ref run() must be called before using this function. 848 848 const PredMap &predMap() const { return *_pred;} 849 849 850 850 ///Checks if a node is reachable from the root. 851 851 … … 863 863 /// 864 864 bool processed(Node v) { return (*_heap_cross_ref)[v] == Heap::POST_HEAP; } 865 865 866 866 ///@} 867 867 }; … … 870 870 871 871 872 872 873 873 ///Default traits class of Dijkstra function. 874 874 … … 879 879 struct DijkstraWizardDefaultTraits 880 880 { 881 ///The digraph type the algorithm runs on. 881 ///The digraph type the algorithm runs on. 882 882 typedef GR Digraph; 883 883 ///The type of the map that stores the arc lengths. … … 902 902 ///Instantiates a HeapCrossRef. 903 903 904 ///This function instantiates a \ref HeapCrossRef. 905 /// \param G is the digraph, to which we would like to define the 904 ///This function instantiates a \ref HeapCrossRef. 905 /// \param G is the digraph, to which we would like to define the 906 906 /// HeapCrossRef. 907 907 /// \todo The digraph alone may be insufficient for the initialization 908 static HeapCrossRef *createHeapCrossRef(const GR &G) 908 static HeapCrossRef *createHeapCrossRef(const GR &G) 909 909 { 910 910 return new HeapCrossRef(G); 911 911 } 912 912 913 913 ///The heap type used by Dijkstra algorithm. 914 914 … … 918 918 ///\sa Dijkstra 919 919 typedef BinHeap<typename LM::Value, typename GR::template NodeMap<int>, 920 921 922 static Heap *createHeap(HeapCrossRef& R) 920 std::less<Value> > Heap; 921 922 static Heap *createHeap(HeapCrossRef& R) 923 923 { 924 924 return new Heap(R); … … 927 927 ///\brief The type of the map that stores the last 928 928 ///arcs of the shortest paths. 929 /// 929 /// 930 930 ///The type of the map that stores the last 931 931 ///arcs of the shortest paths. … … 934 934 typedef NullMap <typename GR::Node,typename GR::Arc> PredMap; 935 935 ///Instantiates a PredMap. 936 937 ///This function instantiates a \ref PredMap. 936 937 ///This function instantiates a \ref PredMap. 938 938 ///\param g is the digraph, to which we would like to define the PredMap. 939 939 ///\todo The digraph alone may be insufficient for the initialization 940 940 #ifdef DOXYGEN 941 static PredMap *createPredMap(const GR &g) 941 static PredMap *createPredMap(const GR &g) 942 942 #else 943 static PredMap *createPredMap(const GR &) 943 static PredMap *createPredMap(const GR &) 944 944 #endif 945 945 { … … 947 947 } 948 948 ///The type of the map that stores whether a nodes is processed. 949 949 950 950 ///The type of the map that stores whether a nodes is processed. 951 951 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 956 956 typedef NullMap<typename Digraph::Node,bool> ProcessedMap; 957 957 ///Instantiates a ProcessedMap. 958 959 ///This function instantiates a \ref ProcessedMap. 958 959 ///This function instantiates a \ref ProcessedMap. 960 960 ///\param g is the digraph, to which 961 961 ///we would like to define the \ref ProcessedMap … … 969 969 } 970 970 ///The type of the map that stores the dists of the nodes. 971 971 972 972 ///The type of the map that stores the dists of the nodes. 973 973 ///It must meet the \ref concepts::WriteMap "WriteMap" concept. … … 975 975 typedef NullMap<typename Digraph::Node,typename LM::Value> DistMap; 976 976 ///Instantiates a DistMap. 977 978 ///This function instantiates a \ref DistMap. 977 978 ///This function instantiates a \ref DistMap. 979 979 ///\param g is the digraph, to which we would like to define the \ref DistMap 980 980 #ifdef DOXYGEN … … 987 987 } 988 988 }; 989 989 990 990 /// Default traits used by \ref DijkstraWizard 991 991 … … 1019 1019 public: 1020 1020 /// Constructor. 1021 1021 1022 1022 /// This constructor does not require parameters, therefore it initiates 1023 1023 /// all of the attributes to default values (0, INVALID). 1024 1024 DijkstraWizardBase() : _g(0), _length(0), _pred(0), 1025 1025 _dist(0), _source(INVALID) {} 1026 1026 1027 1027 /// Constructor. 1028 1028 1029 1029 /// This constructor requires some parameters, 1030 1030 /// listed in the parameters list. … … 1034 1034 /// \param s is the initial value of \ref _source 1035 1035 DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) : 1036 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))), 1037 _length(reinterpret_cast<void*>(const_cast<LM*>(&l))), 1036 _g(reinterpret_cast<void*>(const_cast<GR*>(&g))), 1037 _length(reinterpret_cast<void*>(const_cast<LM*>(&l))), 1038 1038 _pred(0), _dist(0), _source(s) {} 1039 1039 1040 1040 }; 1041 1041 1042 1042 /// A class to make the usage of Dijkstra algorithm easier 1043 1043 … … 1057 1057 /// 1058 1058 /// It does not have own \ref run method. When its \ref run method is called 1059 /// it initiates a plain \ref Dijkstra class, and calls the \ref 1059 /// it initiates a plain \ref Dijkstra class, and calls the \ref 1060 1060 /// Dijkstra::run method of it. 1061 1061 template<class TR> … … 1074 1074 //\e 1075 1075 typedef typename Digraph::OutArcIt OutArcIt; 1076 1076 1077 1077 ///The type of the map that stores the arc lengths. 1078 1078 typedef typename TR::LengthMap LengthMap; … … 1103 1103 1104 1104 ///Runs Dijkstra algorithm from a given node. 1105 1105 1106 1106 ///Runs Dijkstra algorithm from a given node. 1107 1107 ///The node can be given by the \ref source function. … … 1109 1109 { 1110 1110 if(Base::_source==INVALID) throw UninitializedParameter(); 1111 Dijkstra<Digraph,LengthMap,TR> 1112 1111 Dijkstra<Digraph,LengthMap,TR> 1112 dij(*reinterpret_cast<const Digraph*>(Base::_g), 1113 1113 *reinterpret_cast<const LengthMap*>(Base::_length)); 1114 1114 if(Base::_pred) dij.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); … … 1133 1133 DefPredMapBase(const TR &b) : TR(b) {} 1134 1134 }; 1135 1135 1136 1136 ///\brief \ref named-templ-param "Named parameter" 1137 1137 ///function for setting PredMap type … … 1141 1141 /// 1142 1142 template<class T> 1143 DijkstraWizard<DefPredMapBase<T> > predMap(const T &t) 1143 DijkstraWizard<DefPredMapBase<T> > predMap(const T &t) 1144 1144 { 1145 1145 Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); 1146 1146 return DijkstraWizard<DefPredMapBase<T> >(*this); 1147 1147 } 1148 1148 1149 1149 template<class T> 1150 1150 struct DefDistMapBase : public Base { … … 1153 1153 DefDistMapBase(const TR &b) : TR(b) {} 1154 1154 }; 1155 1155 1156 1156 ///\brief \ref named-templ-param "Named parameter" 1157 1157 ///function for setting DistMap type … … 1161 1161 /// 1162 1162 template<class T> 1163 DijkstraWizard<DefDistMapBase<T> > distMap(const T &t) 1163 DijkstraWizard<DefDistMapBase<T> > distMap(const T &t) 1164 1164 { 1165 1165 Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); 1166 1166 return DijkstraWizard<DefDistMapBase<T> >(*this); 1167 1167 } 1168 1168 1169 1169 /// Sets the source node, from which the Dijkstra algorithm runs. 1170 1170 1171 1171 /// Sets the source node, from which the Dijkstra algorithm runs. 1172 1172 /// \param s is the source node. 1173 DijkstraWizard<TR> &source(Node s) 1173 DijkstraWizard<TR> &source(Node s) 1174 1174 { 1175 1175 Base::_source=s; 1176 1176 return *this; 1177 1177 } 1178 1178 1179 1179 }; 1180 1180 1181 1181 ///Function type interface for Dijkstra algorithm. 1182 1182 -
lemon/dim2.h
r49 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 25 25 ///\ingroup misc 26 26 ///\file 27 ///\brief A simple two dimensional vector and a bounding box implementation 27 ///\brief A simple two dimensional vector and a bounding box implementation 28 28 /// 29 29 /// The class \ref lemon::dim2::Point "dim2::Point" implements … … 60 60 T x; 61 61 ///Second coordinate 62 T y; 63 62 T y; 63 64 64 ///Default constructor 65 65 Point() {} … … 71 71 72 72 ///The dimension of the vector. 73 ///This function always returns 2. 73 ///This function always returns 2. 74 74 int size() const { return 2; } 75 75 … … 93 93 return x*x+y*y; 94 94 } 95 95 96 96 ///Increment the left hand side by \c u 97 97 Point<T>& operator +=(const Point<T>& u) { … … 100 100 return *this; 101 101 } 102 102 103 103 ///Decrement the left hand side by \c u 104 104 Point<T>& operator -=(const Point<T>& u) { … … 121 121 return *this; 122 122 } 123 123 124 124 ///Return the scalar product of two vectors 125 125 T operator *(const Point<T>& u) const { 126 126 return x*u.x+y*u.y; 127 127 } 128 128 129 129 ///Return the sum of two vectors 130 130 Point<T> operator+(const Point<T> &u) const { … … 170 170 }; 171 171 172 ///Return a Point 172 ///Return a Point 173 173 174 174 ///Return a Point. … … 260 260 } 261 261 262 262 263 263 264 264 /// A class to calculate or store the bounding box of plainvectors. … … 271 271 bool _empty; 272 272 public: 273 273 274 274 ///Default constructor: creates an empty bounding box 275 275 BoundingBox() { _empty = true; } … … 277 277 ///Construct an instance from one point 278 278 BoundingBox(Point<T> a) { bottom_left=top_right=a; _empty = false; } 279 279 280 280 ///Construct an instance from two points 281 281 282 282 ///Construct an instance from two points. 283 283 ///\param a The bottom left corner. … … 287 287 BoundingBox(Point<T> a,Point<T> b) 288 288 { 289 290 291 292 } 293 289 bottom_left=a; 290 top_right=b; 291 _empty = false; 292 } 293 294 294 ///Construct an instance from four numbers 295 295 … … 300 300 ///\param t The top of the box. 301 301 ///\warning The left side must be no more than the right side and 302 ///bottom must be no more than the top. 302 ///bottom must be no more than the top. 303 303 BoundingBox(T l,T b,T r,T t) 304 304 { 305 306 307 308 } 309 305 bottom_left=Point<T>(l,b); 306 top_right=Point<T>(r,t); 307 _empty = false; 308 } 309 310 310 ///Return \c true if the bounding box is empty. 311 311 312 312 ///Return \c true if the bounding box is empty (i.e. return \c false 313 313 ///if at least one point was added to the box or the coordinates of 314 314 ///the box were set). 315 315 /// 316 ///The coordinates of an empty bounding box are not defined. 316 ///The coordinates of an empty bounding box are not defined. 317 317 bool empty() const { 318 318 return _empty; 319 319 } 320 320 321 321 ///Make the BoundingBox empty 322 322 void clear() { … … 337 337 ///It should only be used for non-empty box. 338 338 void bottomLeft(Point<T> p) { 339 339 bottom_left = p; 340 340 } 341 341 … … 353 353 ///It should only be used for non-empty box. 354 354 void topRight(Point<T> p) { 355 355 top_right = p; 356 356 } 357 357 … … 369 369 ///It should only be used for non-empty box. 370 370 void bottomRight(Point<T> p) { 371 372 373 } 374 371 top_right.x = p.x; 372 bottom_left.y = p.y; 373 } 374 375 375 ///Give back the top left corner of the box 376 376 … … 386 386 ///It should only be used for non-empty box. 387 387 void topLeft(Point<T> p) { 388 389 388 top_right.y = p.y; 389 bottom_left.x = p.x; 390 390 } 391 391 … … 403 403 ///It should only be used for non-empty box. 404 404 void bottom(T t) { 405 405 bottom_left.y = t; 406 406 } 407 407 … … 419 419 ///It should only be used for non-empty box. 420 420 void top(T t) { 421 421 top_right.y = t; 422 422 } 423 423 … … 429 429 return bottom_left.x; 430 430 } 431 431 432 432 ///Set the left side of the box 433 433 … … 435 435 ///It should only be used for non-empty box. 436 436 void left(T t) { 437 437 bottom_left.x = t; 438 438 } 439 439 … … 451 451 ///It should only be used for non-empty box. 452 452 void right(T t) { 453 453 top_right.x = t; 454 454 } 455 455 … … 479 479 } 480 480 } 481 481 482 482 ///Increments a bounding box with a point 483 483 … … 497 497 return *this; 498 498 } 499 499 500 500 ///Increments a bounding box to contain another bounding box 501 501 502 502 ///Increments a bounding box to contain another bounding box. 503 503 /// … … 505 505 if ( !u.empty() ){ 506 506 this->add(u.bottomLeft()); 507 507 this->add(u.topRight()); 508 508 } 509 509 return *this; 510 510 } 511 511 512 512 ///Intersection of two bounding boxes 513 513 … … 517 517 BoundingBox b; 518 518 if (this->_empty || u._empty) { 519 520 521 522 523 524 525 526 527 } 519 b._empty = true; 520 } else { 521 b.bottom_left.x = std::max(this->bottom_left.x,u.bottom_left.x); 522 b.bottom_left.y = std::max(this->bottom_left.y,u.bottom_left.y); 523 b.top_right.x = std::min(this->top_right.x,u.top_right.x); 524 b.top_right.y = std::min(this->top_right.y,u.top_right.y); 525 b._empty = b.bottom_left.x > b.top_right.x || 526 b.bottom_left.y > b.top_right.y; 527 } 528 528 return b; 529 529 } … … 538 538 /// 539 539 template<class M> 540 class XMap 540 class XMap 541 541 { 542 542 M& _map; … … 550 550 void set(Key k,Value v) {_map.set(k,typename M::Value(v,_map[k].y));} 551 551 }; 552 552 553 553 ///Returns an \ref XMap class 554 554 … … 557 557 ///\ingroup maps 558 558 ///\relates XMap 559 template<class M> 560 inline XMap<M> xMap(M &m) 559 template<class M> 560 inline XMap<M> xMap(M &m) 561 561 { 562 562 return XMap<M>(m); 563 563 } 564 564 565 template<class M> 566 inline XMap<M> xMap(const M &m) 565 template<class M> 566 inline XMap<M> xMap(const M &m) 567 567 { 568 568 return XMap<M>(m); … … 575 575 /// 576 576 template<class M> 577 class ConstXMap 577 class ConstXMap 578 578 { 579 579 const M& _map; … … 586 586 Value operator[](Key k) const {return _map[k].x;} 587 587 }; 588 588 589 589 ///Returns a \ref ConstXMap class 590 590 … … 593 593 ///\ingroup maps 594 594 ///\relates ConstXMap 595 template<class M> 596 inline ConstXMap<M> xMap(const M &m) 595 template<class M> 596 inline ConstXMap<M> xMap(const M &m) 597 597 { 598 598 return ConstXMap<M>(m); … … 600 600 601 601 ///Map of y-coordinates of a \ref Point "Point"-map 602 602 603 603 ///\ingroup maps 604 604 ///Map of y-coordinates of a \ref Point "Point"-map. 605 605 /// 606 606 template<class M> 607 class YMap 607 class YMap 608 608 { 609 609 M& _map; … … 624 624 ///\ingroup maps 625 625 ///\relates YMap 626 template<class M> 627 inline YMap<M> yMap(M &m) 626 template<class M> 627 inline YMap<M> yMap(M &m) 628 628 { 629 629 return YMap<M>(m); 630 630 } 631 631 632 template<class M> 633 inline YMap<M> yMap(const M &m) 632 template<class M> 633 inline YMap<M> yMap(const M &m) 634 634 { 635 635 return YMap<M>(m); … … 642 642 /// 643 643 template<class M> 644 class ConstYMap 644 class ConstYMap 645 645 { 646 646 const M& _map; … … 653 653 Value operator[](Key k) const {return _map[k].y;} 654 654 }; 655 655 656 656 ///Returns a \ref ConstYMap class 657 657 … … 660 660 ///\ingroup maps 661 661 ///\relates ConstYMap 662 template<class M> 663 inline ConstYMap<M> yMap(const M &m) 662 template<class M> 663 inline ConstYMap<M> yMap(const M &m) 664 664 { 665 665 return ConstYMap<M>(m); … … 674 674 ///\ingroup maps 675 675 template<class M> 676 class NormSquareMap 676 class NormSquareMap 677 677 { 678 678 const M& _map; … … 685 685 Value operator[](Key k) const {return _map[k].normSquare();} 686 686 }; 687 687 688 688 ///Returns a \ref NormSquareMap class 689 689 … … 692 692 ///\ingroup maps 693 693 ///\relates NormSquareMap 694 template<class M> 695 inline NormSquareMap<M> normSquareMap(const M &m) 694 template<class M> 695 inline NormSquareMap<M> normSquareMap(const M &m) 696 696 { 697 697 return NormSquareMap<M>(m); … … 701 701 702 702 } //namespce dim2 703 703 704 704 } //namespace lemon 705 705 -
lemon/error.h
r108 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 46 46 ExceptionMember() throw() { 47 47 try { 48 48 ptr.reset(new Type()); 49 49 } catch (...) {} 50 50 } … … 52 52 ExceptionMember(const Type& type) throw() { 53 53 try { 54 55 56 54 ptr.reset(new Type()); 55 if (ptr.get() == 0) return; 56 *ptr = type; 57 57 } catch (...) {} 58 58 } … … 60 60 ExceptionMember(const ExceptionMember& copy) throw() { 61 61 try { 62 63 64 65 62 if (!copy.valid()) return; 63 ptr.reset(new Type()); 64 if (ptr.get() == 0) return; 65 *ptr = copy.get(); 66 66 } catch (...) {} 67 67 } … … 70 70 if (ptr.get() == 0) return; 71 71 try { 72 73 72 if (!copy.valid()) return; 73 *ptr = copy.get(); 74 74 } catch (...) {} 75 75 } … … 78 78 if (ptr.get() == 0) return; 79 79 try { 80 80 *ptr = type; 81 81 } catch (...) {} 82 82 } … … 110 110 bool init() throw() { 111 111 try { 112 112 buf.reset(new std::ostringstream); 113 113 } 114 114 catch(...) { 115 115 buf.reset(); 116 116 } 117 117 return buf.get(); … … 143 143 144 144 try { 145 145 *buf << t; 146 146 } 147 147 catch(...) { 148 148 buf.reset(); 149 149 } 150 150 return *this; … … 157 157 const char* mes = 0; 158 158 try { 159 159 mes = buf->str().c_str(); 160 160 } 161 161 catch(...) {} … … 255 255 ///\e 256 256 DataFormatError(const std::string &file_name, int line_num, 257 257 const char *the_message) 258 258 : _message(the_message), _line(line_num) { file(file_name); } 259 259 … … 270 270 const char* message() const { 271 271 if (_message.valid() && !_message.get().empty()) { 272 272 return _message.get().c_str(); 273 273 } else { 274 274 return 0; 275 275 } 276 276 } … … 281 281 const char* file() const { 282 282 if (_file.valid() && !_file.get().empty()) { 283 283 return _file.get().c_str(); 284 284 } else { 285 286 } 287 } 288 289 ///\e 290 virtual const char* what() const throw() { 291 try { 292 293 294 295 296 297 298 299 300 301 302 285 return 0; 286 } 287 } 288 289 ///\e 290 virtual const char* what() const throw() { 291 try { 292 std::ostringstream ostr; 293 ostr << "lemon:DataFormatError" << ": "; 294 if (message()) ostr << message(); 295 if( file() || line() != 0 ) { 296 ostr << " ("; 297 if( file() ) ostr << "in file '" << file() << "'"; 298 if( file() && line() != 0 ) ostr << " "; 299 if( line() != 0 ) ostr << "at line " << line(); 300 ostr << ")"; 301 } 302 _message_holder.set(ostr.str()); 303 303 } 304 304 catch (...) {} … … 334 334 const char* file() const { 335 335 if (_file.valid() && !_file.get().empty()) { 336 336 return _file.get().c_str(); 337 337 } else { 338 339 } 340 } 341 342 ///\e 343 virtual const char* what() const throw() { 344 try { 345 346 347 348 338 return 0; 339 } 340 } 341 342 ///\e 343 virtual const char* what() const throw() { 344 try { 345 std::ostringstream ostr; 346 ostr << "lemon::FileOpenError" << ": "; 347 ostr << "Cannot open file - " << file(); 348 _message_holder.set(ostr.str()); 349 349 } 350 350 catch (...) {} … … 382 382 const char* message() const { 383 383 if (_message.valid()) { 384 384 return _message.get().c_str(); 385 385 } else { 386 386 return 0; 387 387 } 388 388 } … … 393 393 const char* file() const { 394 394 if (_file.valid()) { 395 395 return _file.get().c_str(); 396 396 } else { 397 398 } 399 } 400 401 ///\e 402 virtual const char* what() const throw() { 403 try { 404 405 406 407 397 return 0; 398 } 399 } 400 401 ///\e 402 virtual const char* what() const throw() { 403 try { 404 std::ostringstream ostr; 405 if (message()) ostr << message(); 406 if (file()) ostr << "(when reading file '" << file() << "')"; 407 _message_holder.set(ostr.str()); 408 408 } 409 409 catch (...) {} -
lemon/graph_to_eps.h
r206 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 61 61 }; 62 62 } 63 63 64 64 ///Default traits class of \ref GraphToEps 65 65 … … 77 77 typedef typename Graph::InArcIt InArcIt; 78 78 typedef typename Graph::OutArcIt OutArcIt; 79 79 80 80 81 81 const Graph &g; 82 82 83 83 std::ostream& os; 84 84 85 85 typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType; 86 86 CoordsMapType _coords; … … 94 94 95 95 double _arcWidthScale; 96 96 97 97 double _nodeScale; 98 98 double _xBorder, _yBorder; 99 99 double _scale; 100 100 double _nodeBorderQuotient; 101 101 102 102 bool _drawArrows; 103 103 double _arrowLength, _arrowWidth; 104 104 105 105 bool _showNodes, _showArcs; 106 106 … … 109 109 110 110 bool _showNodeText; 111 ConstMap<typename Graph::Node,bool > _nodeTexts; 111 ConstMap<typename Graph::Node,bool > _nodeTexts; 112 112 double _nodeTextSize; 113 113 114 114 bool _showNodePsText; 115 ConstMap<typename Graph::Node,bool > _nodePsTexts; 115 ConstMap<typename Graph::Node,bool > _nodePsTexts; 116 116 char *_nodePsTextsPreamble; 117 117 118 118 bool _undirected; 119 119 … … 125 125 std::string _copyright; 126 126 127 enum NodeTextColorType 127 enum NodeTextColorType 128 128 { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType; 129 129 ConstMap<typename Graph::Node,Color > _nodeTextColors; … … 147 147 ///will be explicitly deallocated by the destructor. 148 148 DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout, 149 149 bool _pros=false) : 150 150 g(_g), os(_os), 151 151 _coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0), … … 176 176 /// 177 177 ///For detailed examples see the \ref graph_to_eps_demo.cc demo file. 178 template<class T> class GraphToEps : public T 178 template<class T> class GraphToEps : public T 179 179 { 180 180 // Can't believe it is required by the C++ standard … … 195 195 using T::_scale; 196 196 using T::_nodeBorderQuotient; 197 197 198 198 using T::_drawArrows; 199 199 using T::_arrowLength; 200 200 using T::_arrowWidth; 201 201 202 202 using T::_showNodes; 203 203 using T::_showArcs; … … 207 207 208 208 using T::_showNodeText; 209 using T::_nodeTexts; 209 using T::_nodeTexts; 210 210 using T::_nodeTextSize; 211 211 212 212 using T::_showNodePsText; 213 using T::_nodePsTexts; 213 using T::_nodePsTexts; 214 214 using T::_nodePsTextsPreamble; 215 215 216 216 using T::_undirected; 217 217 … … 262 262 ///Node shapes. 263 263 /// 264 enum NodeShapes { 264 enum NodeShapes { 265 265 /// = 0 266 266 ///\image html nodeshape_0.png 267 267 ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm 268 CIRCLE=0, 268 CIRCLE=0, 269 269 /// = 1 270 270 ///\image html nodeshape_1.png 271 271 ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm 272 272 /// 273 SQUARE=1, 273 SQUARE=1, 274 274 /// = 2 275 275 ///\image html nodeshape_2.png … … 294 294 public: 295 295 arcLess(const Graph &_g) : g(_g) {} 296 bool operator()(Arc a,Arc b) const 296 bool operator()(Arc a,Arc b) const 297 297 { 298 298 Node ai=std::min(g.source(a),g.target(a)); … … 301 301 Node ba=std::max(g.source(b),g.target(b)); 302 302 return ai<bi || 303 (ai==bi && (aa < ba || 304 303 (ai==bi && (aa < ba || 304 (aa==ba && ai==g.source(a) && bi==g.target(b)))); 305 305 } 306 306 }; … … 308 308 { 309 309 return (g.source(e)==g.source(f)&& 310 310 g.target(e)==g.target(f)) || 311 311 (g.source(e)==g.target(f)&& 312 312 g.target(e)==g.source(f)); 313 313 } 314 314 template<class TT> 315 static std::string psOut(const dim2::Point<TT> &p) 315 static std::string psOut(const dim2::Point<TT> &p) 316 316 { 317 std::ostringstream os; 317 std::ostringstream os; 318 318 os << p.x << ' ' << p.y; 319 319 return os.str(); 320 320 } 321 static std::string psOut(const Color &c) 321 static std::string psOut(const Color &c) 322 322 { 323 std::ostringstream os; 323 std::ostringstream os; 324 324 os << c.red() << ' ' << c.green() << ' ' << c.blue(); 325 325 return os.str(); 326 326 } 327 327 328 328 public: 329 329 GraphToEps(const T &t) : T(t), dontPrint(false) {}; 330 330 331 331 template<class X> struct CoordsTraits : public T { 332 332 typedef X CoordsMapType; … … 338 338 ///Sets the map of the node coordinates. 339 339 ///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or 340 ///\ref dim2::Point "dim2::Point<int>" values. 340 ///\ref dim2::Point "dim2::Point<int>" values. 341 341 template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) { 342 342 dontPrint=true; … … 350 350 351 351 ///Sets the map of the node sizes. 352 ///\param x must be a node map with \c double (or convertible) values. 352 ///\param x must be a node map with \c double (or convertible) values. 353 353 template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x) 354 354 { … … 365 365 ///The available shape values 366 366 ///can be found in \ref NodeShapes "enum NodeShapes". 367 ///\param x must be a node map with \c int (or convertible) values. 367 ///\param x must be a node map with \c int (or convertible) values. 368 368 ///\sa NodeShapes 369 369 template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x) … … 380 380 ///Sets the text printed on the nodes. 381 381 ///\param x must be a node map with type that can be pushed to a standard 382 ///\c ostream. 382 ///\c ostream. 383 383 template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x) 384 384 { … … 418 418 419 419 ///Sets the map of the arc widths. 420 ///\param x must be an arc map with \c double (or convertible) values. 420 ///\param x must be an arc map with \c double (or convertible) values. 421 421 template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x) 422 422 { … … 448 448 449 449 ///Sets the map of the node text colors. 450 ///\param x must be a node map with \ref Color values. 450 ///\param x must be a node map with \ref Color values. 451 451 /// 452 452 ///\sa Palette … … 466 466 467 467 ///Sets the map of the arc colors. 468 ///\param x must be an arc map with \ref Color values. 468 ///\param x must be an arc map with \ref Color values. 469 469 /// 470 470 ///\sa Palette … … 478 478 479 479 ///Sets a global scale factor for node sizes. 480 /// 480 /// 481 481 /// If nodeSizes() is not given, this function simply sets the node 482 482 /// sizes to \c d. If nodeSizes() is given, but … … 569 569 ///Sets the width of the arrowheads 570 570 GraphToEps<T> &arrowWidth(double d=.3) {_arrowWidth*=d;return *this;} 571 571 572 572 ///Scales the drawing to fit to A4 page 573 573 GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;} 574 574 575 575 ///Enables parallel arcs 576 576 GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;} 577 577 578 578 ///Sets the distance between parallel arcs 579 579 GraphToEps<T> &parArcDist(double d) {_parArcDist*=d;return *this;} 580 580 581 581 ///Hides the arcs 582 582 GraphToEps<T> &hideArcs(bool b=true) {_showArcs=!b;return *this;} 583 583 ///Hides the nodes 584 584 GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;} 585 585 586 586 ///Sets the size of the node texts 587 587 GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;} … … 601 601 602 602 ///Gives a preamble block for node Postscript block. 603 603 604 604 ///Gives a preamble block for node Postscript block. 605 605 /// … … 626 626 ///\sa undirected() 627 627 GraphToEps<T> &directed(bool b=true) {_undirected=!b;return *this;} 628 628 629 629 ///Sets the title. 630 630 … … 641 641 642 642 protected: 643 bool isInsideNode(dim2::Point<double> p, double r,int t) 643 bool isInsideNode(dim2::Point<double> p, double r,int t) 644 644 { 645 645 switch(t) { … … 658 658 public: 659 659 ~GraphToEps() { } 660 660 661 661 ///Draws the graph. 662 662 … … 669 669 const double EPSILON=1e-9; 670 670 if(dontPrint) return; 671 671 672 672 _graph_to_eps_bits::_NegY<typename T::CoordsMapType> 673 673 mycoords(_coords,_negY); … … 678 678 os << "%%Creator: LEMON, graphToEps()\n"; 679 679 680 { 681 #ifndef WIN32 680 { 681 #ifndef WIN32 682 682 timeval tv; 683 683 gettimeofday(&tv, 0); … … 689 689 SYSTEMTIME time; 690 690 char buf1[11], buf2[9], buf3[5]; 691 691 692 692 GetSystemTime(&time); 693 if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &time, 694 695 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &time, 696 697 GetDateFormat(LOCALE_USER_DEFAULT, 0, &time, 698 699 os << "%%CreationDate: " << buf1 << ' ' 700 701 } 693 if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &time, 694 "ddd MMM dd", buf1, 11) && 695 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &time, 696 "HH':'mm':'ss", buf2, 9) && 697 GetDateFormat(LOCALE_USER_DEFAULT, 0, &time, 698 "yyyy", buf3, 5)) { 699 os << "%%CreationDate: " << buf1 << ' ' 700 << buf2 << ' ' << buf3 << std::endl; 701 } 702 702 #endif 703 703 } … … 706 706 double max_w=0; 707 707 for(ArcIt e(g);e!=INVALID;++e) 708 708 max_w=std::max(double(_arcWidths[e]),max_w); 709 709 //\todo better 'epsilon' would be nice here. 710 710 if(max_w>EPSILON) { 711 711 _arcWidthScale/=max_w; 712 712 } 713 713 } … … 716 716 double max_s=0; 717 717 for(NodeIt n(g);n!=INVALID;++n) 718 718 max_s=std::max(double(_nodeSizes[n]),max_s); 719 719 //\todo better 'epsilon' would be nice here. 720 720 if(max_s>EPSILON) { 721 721 _nodeScale/=max_s; 722 722 } 723 723 } … … 728 728 for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]); 729 729 if (bb.empty()) { 730 730 bb = dim2::BoundingBox<double>(dim2::Point<double>(0,0)); 731 731 } 732 732 diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare()); … … 735 735 if(!_absoluteArcWidths) _arcWidthScale*=diag_len; 736 736 } 737 737 738 738 dim2::BoundingBox<double> bb; 739 739 for(NodeIt n(g);n!=INVALID;++n) { … … 744 744 case SQUARE: 745 745 case DIAMOND: 746 747 748 746 bb.add(p+mycoords[n]); 747 bb.add(-p+mycoords[n]); 748 break; 749 749 case MALE: 750 751 752 750 bb.add(-p+mycoords[n]); 751 bb.add(dim2::Point<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]); 752 break; 753 753 case FEMALE: 754 755 756 754 bb.add(p+mycoords[n]); 755 bb.add(dim2::Point<double>(-ns,-3.01*ns)+mycoords[n]); 756 break; 757 757 } 758 758 } … … 760 760 bb = dim2::BoundingBox<double>(dim2::Point<double>(0,0)); 761 761 } 762 762 763 763 if(_scaleToA4) 764 764 os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n"; 765 765 else { 766 766 if(_preScale) { 767 768 769 767 //Rescale so that BoundingBox won't be neither to big nor too small. 768 while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10; 769 while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10; 770 770 } 771 771 772 772 os << "%%BoundingBox: " 773 774 775 776 777 } 778 773 << int(floor(bb.left() * _scale - _xBorder)) << ' ' 774 << int(floor(bb.bottom() * _scale - _yBorder)) << ' ' 775 << int(ceil(bb.right() * _scale + _xBorder)) << ' ' 776 << int(ceil(bb.top() * _scale + _yBorder)) << '\n'; 777 } 778 779 779 os << "%%EndComments\n"; 780 780 781 781 //x1 y1 x2 y2 x3 y3 cr cg cb w 782 782 os << "/lb { setlinewidth setrgbcolor newpath moveto\n" … … 832 832 << " setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n" 833 833 << " } bind def\n"; 834 834 835 835 836 836 os << "/arrl " << _arrowLength << " def\n"; … … 841 841 os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n" 842 842 << " /w exch def /len exch def\n" 843 // 843 // << " 0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke" 844 844 << " newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n" 845 845 << " len w sub arrl sub dx dy lrl\n" … … 858 858 if(_scaleToA4) 859 859 if(bb.height()>bb.width()) { 860 861 862 863 864 865 866 860 double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(), 861 (A4WIDTH-2*A4BORDER)/bb.width()); 862 os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' ' 863 << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER 864 << " translate\n" 865 << sc << " dup scale\n" 866 << -bb.left() << ' ' << -bb.bottom() << " translate\n"; 867 867 } 868 868 else { 869 870 871 872 873 << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER 874 875 876 << -bb.left() << ' ' << -bb.top() << " translate\n"; 877 869 //\todo Verify centering 870 double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(), 871 (A4WIDTH-2*A4BORDER)/bb.height()); 872 os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' ' 873 << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER 874 << " translate\n" 875 << sc << " dup scale\n90 rotate\n" 876 << -bb.left() << ' ' << -bb.top() << " translate\n"; 877 } 878 878 else if(_scale!=1.0) os << _scale << " dup scale\n"; 879 879 880 880 if(_showArcs) { 881 os << "%Arcs:\ngsave\n"; 881 os << "%Arcs:\ngsave\n"; 882 882 if(_enableParallel) { 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 double l=std::sqrt(dvec.normSquare()); 902 903 904 905 // 906 907 // 908 // 909 // 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 dim2::Point<double> linend=bez((t1+t2)/2); 936 937 // 938 // 939 // 940 // 941 // 942 // 943 // 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 883 std::vector<Arc> el; 884 for(ArcIt e(g);e!=INVALID;++e) 885 if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0 886 &&g.source(e)!=g.target(e)) 887 el.push_back(e); 888 std::sort(el.begin(),el.end(),arcLess(g)); 889 890 typename std::vector<Arc>::iterator j; 891 for(typename std::vector<Arc>::iterator i=el.begin();i!=el.end();i=j) { 892 for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ; 893 894 double sw=0; 895 for(typename std::vector<Arc>::iterator e=i;e!=j;++e) 896 sw+=_arcWidths[*e]*_arcWidthScale+_parArcDist; 897 sw-=_parArcDist; 898 sw/=-2.0; 899 dim2::Point<double> 900 dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]); 901 double l=std::sqrt(dvec.normSquare()); 902 //\todo better 'epsilon' would be nice here. 903 dim2::Point<double> d(dvec/std::max(l,EPSILON)); 904 dim2::Point<double> m; 905 // m=dim2::Point<double>(mycoords[g.target(*i)]+mycoords[g.source(*i)])/2.0; 906 907 // m=dim2::Point<double>(mycoords[g.source(*i)])+ 908 // dvec*(double(_nodeSizes[g.source(*i)])/ 909 // (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)])); 910 911 m=dim2::Point<double>(mycoords[g.source(*i)])+ 912 d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0; 913 914 for(typename std::vector<Arc>::iterator e=i;e!=j;++e) { 915 sw+=_arcWidths[*e]*_arcWidthScale/2.0; 916 dim2::Point<double> mm=m+rot90(d)*sw/.75; 917 if(_drawArrows) { 918 int node_shape; 919 dim2::Point<double> s=mycoords[g.source(*e)]; 920 dim2::Point<double> t=mycoords[g.target(*e)]; 921 double rn=_nodeSizes[g.target(*e)]*_nodeScale; 922 node_shape=_nodeShapes[g.target(*e)]; 923 dim2::Bezier3 bez(s,mm,mm,t); 924 double t1=0,t2=1; 925 for(int ii=0;ii<INTERPOL_PREC;++ii) 926 if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2; 927 else t1=(t1+t2)/2; 928 dim2::Point<double> apoint=bez((t1+t2)/2); 929 rn = _arrowLength+_arcWidths[*e]*_arcWidthScale; 930 rn*=rn; 931 t2=(t1+t2)/2;t1=0; 932 for(int ii=0;ii<INTERPOL_PREC;++ii) 933 if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2; 934 else t2=(t1+t2)/2; 935 dim2::Point<double> linend=bez((t1+t2)/2); 936 bez=bez.before((t1+t2)/2); 937 // rn=_nodeSizes[g.source(*e)]*_nodeScale; 938 // node_shape=_nodeShapes[g.source(*e)]; 939 // t1=0;t2=1; 940 // for(int i=0;i<INTERPOL_PREC;++i) 941 // if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t1=(t1+t2)/2; 942 // else t2=(t1+t2)/2; 943 // bez=bez.after((t1+t2)/2); 944 os << _arcWidths[*e]*_arcWidthScale << " setlinewidth " 945 << _arcColors[*e].red() << ' ' 946 << _arcColors[*e].green() << ' ' 947 << _arcColors[*e].blue() << " setrgbcolor newpath\n" 948 << bez.p1.x << ' ' << bez.p1.y << " moveto\n" 949 << bez.p2.x << ' ' << bez.p2.y << ' ' 950 << bez.p3.x << ' ' << bez.p3.y << ' ' 951 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n"; 952 dim2::Point<double> dd(rot90(linend-apoint)); 953 dd*=(.5*_arcWidths[*e]*_arcWidthScale+_arrowWidth)/ 954 std::sqrt(dd.normSquare()); 955 os << "newpath " << psOut(apoint) << " moveto " 956 << psOut(linend+dd) << " lineto " 957 << psOut(linend-dd) << " lineto closepath fill\n"; 958 } 959 else { 960 os << mycoords[g.source(*e)].x << ' ' 961 << mycoords[g.source(*e)].y << ' ' 962 << mm.x << ' ' << mm.y << ' ' 963 << mycoords[g.target(*e)].x << ' ' 964 << mycoords[g.target(*e)].y << ' ' 965 << _arcColors[*e].red() << ' ' 966 << _arcColors[*e].green() << ' ' 967 << _arcColors[*e].blue() << ' ' 968 << _arcWidths[*e]*_arcWidthScale << " lb\n"; 969 } 970 sw+=_arcWidths[*e]*_arcWidthScale/2.0+_parArcDist; 971 } 972 } 973 973 } 974 974 else for(ArcIt e(g);e!=INVALID;++e) 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 } 997 998 999 1000 1001 1002 1003 1004 1005 975 if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0 976 &&g.source(e)!=g.target(e)) { 977 if(_drawArrows) { 978 dim2::Point<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]); 979 double rn=_nodeSizes[g.target(e)]*_nodeScale; 980 int node_shape=_nodeShapes[g.target(e)]; 981 double t1=0,t2=1; 982 for(int i=0;i<INTERPOL_PREC;++i) 983 if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2; 984 else t2=(t1+t2)/2; 985 double l=std::sqrt(d.normSquare()); 986 d/=l; 987 988 os << l*(1-(t1+t2)/2) << ' ' 989 << _arcWidths[e]*_arcWidthScale << ' ' 990 << d.x << ' ' << d.y << ' ' 991 << mycoords[g.source(e)].x << ' ' 992 << mycoords[g.source(e)].y << ' ' 993 << _arcColors[e].red() << ' ' 994 << _arcColors[e].green() << ' ' 995 << _arcColors[e].blue() << " arr\n"; 996 } 997 else os << mycoords[g.source(e)].x << ' ' 998 << mycoords[g.source(e)].y << ' ' 999 << mycoords[g.target(e)].x << ' ' 1000 << mycoords[g.target(e)].y << ' ' 1001 << _arcColors[e].red() << ' ' 1002 << _arcColors[e].green() << ' ' 1003 << _arcColors[e].blue() << ' ' 1004 << _arcWidths[e]*_arcWidthScale << " l\n"; 1005 } 1006 1006 os << "grestore\n"; 1007 1007 } … … 1009 1009 os << "%Nodes:\ngsave\n"; 1010 1010 for(NodeIt n(g);n!=INVALID;++n) { 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1011 os << mycoords[n].x << ' ' << mycoords[n].y << ' ' 1012 << _nodeSizes[n]*_nodeScale << ' ' 1013 << _nodeColors[n].red() << ' ' 1014 << _nodeColors[n].green() << ' ' 1015 << _nodeColors[n].blue() << ' '; 1016 switch(_nodeShapes[n]) { 1017 case CIRCLE: 1018 os<< "nc";break; 1019 case SQUARE: 1020 os<< "nsq";break; 1021 case DIAMOND: 1022 os<< "ndi";break; 1023 case MALE: 1024 os<< "nmale";break; 1025 case FEMALE: 1026 os<< "nfemale";break; 1027 } 1028 os<<'\n'; 1029 1029 } 1030 1030 os << "grestore\n"; … … 1035 1035 os << "(Helvetica) findfont fosi scalefont setfont\n"; 1036 1036 for(NodeIt n(g);n!=INVALID;++n) { 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1037 switch(_nodeTextColorType) { 1038 case DIST_COL: 1039 os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n"; 1040 break; 1041 case DIST_BW: 1042 os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n"; 1043 break; 1044 case CUST_COL: 1045 os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n"; 1046 break; 1047 default: 1048 os << "0 0 0 setrgbcolor\n"; 1049 } 1050 os << mycoords[n].x << ' ' << mycoords[n].y 1051 << " (" << _nodeTexts[n] << ") cshow\n"; 1052 1052 } 1053 1053 os << "grestore\n"; … … 1056 1056 os << "%Node PS blocks:\ngsave\n"; 1057 1057 for(NodeIt n(g);n!=INVALID;++n) 1058 1059 1058 os << mycoords[n].x << ' ' << mycoords[n].y 1059 << " moveto\n" << _nodePsTexts[n] << "\n"; 1060 1060 os << "grestore\n"; 1061 1061 } 1062 1062 1063 1063 os << "grestore\nshowpage\n"; 1064 1064 … … 1093 1093 return autoArcWidthScale(b); 1094 1094 } 1095 1095 1096 1096 ///An alias for absoluteArcWidths() 1097 1097 GraphToEps<T> &absoluteEdgeWidths(bool b=true) … … 1099 1099 return absoluteArcWidths(b); 1100 1100 } 1101 1101 1102 1102 ///An alias for parArcDist() 1103 1103 GraphToEps<T> &parEdgeDist(double d) {return parArcDist(d);} 1104 1104 1105 1105 ///An alias for hideArcs() 1106 1106 GraphToEps<T> &hideEdges(bool b=true) {return hideArcs(b);} … … 1144 1144 ///\sa graphToEps(G &g, const char *file_name) 1145 1145 template<class G> 1146 GraphToEps<DefaultGraphToEpsTraits<G> > 1146 GraphToEps<DefaultGraphToEpsTraits<G> > 1147 1147 graphToEps(G &g, std::ostream& os=std::cout) 1148 1148 { 1149 return 1149 return 1150 1150 GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os)); 1151 1151 } 1152 1152 1153 1153 ///Generates an EPS file from a graph 1154 1154 … … 1160 1160 ///\sa graphToEps(G &g, std::ostream& os) 1161 1161 template<class G> 1162 GraphToEps<DefaultGraphToEpsTraits<G> > 1162 GraphToEps<DefaultGraphToEpsTraits<G> > 1163 1163 graphToEps(G &g,const char *file_name) 1164 1164 { … … 1176 1176 ///\sa graphToEps(G &g, std::ostream& os) 1177 1177 template<class G> 1178 GraphToEps<DefaultGraphToEpsTraits<G> > 1178 GraphToEps<DefaultGraphToEpsTraits<G> > 1179 1179 graphToEps(G &g,const std::string& file_name) 1180 1180 { -
lemon/graph_utils.h
r199 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 47 47 ///This \c \#define creates convenience typedefs for the following types 48 48 ///of \c Digraph: \c Node, \c NodeIt, \c Arc, \c ArcIt, \c InArcIt, 49 ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap, 49 ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap, 50 50 ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap. 51 51 /// … … 53 53 ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS() 54 54 ///macro. 55 #define DIGRAPH_TYPEDEFS(Digraph) 56 typedef Digraph::Node Node; 57 typedef Digraph::NodeIt NodeIt; 58 typedef Digraph::Arc Arc; 59 typedef Digraph::ArcIt ArcIt; 60 typedef Digraph::InArcIt InArcIt; 61 typedef Digraph::OutArcIt OutArcIt; 62 typedef Digraph::NodeMap<bool> BoolNodeMap; 63 typedef Digraph::NodeMap<int> IntNodeMap; 64 typedef Digraph::NodeMap<double> DoubleNodeMap; 65 typedef Digraph::ArcMap<bool> BoolArcMap; 66 typedef Digraph::ArcMap<int> IntArcMap; 55 #define DIGRAPH_TYPEDEFS(Digraph) \ 56 typedef Digraph::Node Node; \ 57 typedef Digraph::NodeIt NodeIt; \ 58 typedef Digraph::Arc Arc; \ 59 typedef Digraph::ArcIt ArcIt; \ 60 typedef Digraph::InArcIt InArcIt; \ 61 typedef Digraph::OutArcIt OutArcIt; \ 62 typedef Digraph::NodeMap<bool> BoolNodeMap; \ 63 typedef Digraph::NodeMap<int> IntNodeMap; \ 64 typedef Digraph::NodeMap<double> DoubleNodeMap; \ 65 typedef Digraph::ArcMap<bool> BoolArcMap; \ 66 typedef Digraph::ArcMap<int> IntArcMap; \ 67 67 typedef Digraph::ArcMap<double> DoubleArcMap 68 68 … … 73 73 ///\note Use this macro, if the graph type is a dependent type, 74 74 ///ie. the graph type depend on a template parameter. 75 #define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph) 76 typedef typename Digraph::Node Node; 77 typedef typename Digraph::NodeIt NodeIt; 78 typedef typename Digraph::Arc Arc; 79 typedef typename Digraph::ArcIt ArcIt; 80 typedef typename Digraph::InArcIt InArcIt; 81 typedef typename Digraph::OutArcIt OutArcIt; 82 typedef typename Digraph::template NodeMap<bool> BoolNodeMap; 83 typedef typename Digraph::template NodeMap<int> IntNodeMap; 84 typedef typename Digraph::template NodeMap<double> DoubleNodeMap; 85 typedef typename Digraph::template ArcMap<bool> BoolArcMap; 86 typedef typename Digraph::template ArcMap<int> IntArcMap; 75 #define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph) \ 76 typedef typename Digraph::Node Node; \ 77 typedef typename Digraph::NodeIt NodeIt; \ 78 typedef typename Digraph::Arc Arc; \ 79 typedef typename Digraph::ArcIt ArcIt; \ 80 typedef typename Digraph::InArcIt InArcIt; \ 81 typedef typename Digraph::OutArcIt OutArcIt; \ 82 typedef typename Digraph::template NodeMap<bool> BoolNodeMap; \ 83 typedef typename Digraph::template NodeMap<int> IntNodeMap; \ 84 typedef typename Digraph::template NodeMap<double> DoubleNodeMap; \ 85 typedef typename Digraph::template ArcMap<bool> BoolArcMap; \ 86 typedef typename Digraph::template ArcMap<int> IntArcMap; \ 87 87 typedef typename Digraph::template ArcMap<double> DoubleArcMap 88 88 89 89 ///Creates convenience typedefs for the graph types and iterators 90 90 … … 97 97 ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS() 98 98 ///macro. 99 #define GRAPH_TYPEDEFS(Graph) 100 DIGRAPH_TYPEDEFS(Graph); 101 typedef Graph::Edge Edge; 102 typedef Graph::EdgeIt EdgeIt; 103 typedef Graph::IncEdgeIt IncEdgeIt; 104 typedef Graph::EdgeMap<bool> BoolEdgeMap; 105 typedef Graph::EdgeMap<int> IntEdgeMap; 99 #define GRAPH_TYPEDEFS(Graph) \ 100 DIGRAPH_TYPEDEFS(Graph); \ 101 typedef Graph::Edge Edge; \ 102 typedef Graph::EdgeIt EdgeIt; \ 103 typedef Graph::IncEdgeIt IncEdgeIt; \ 104 typedef Graph::EdgeMap<bool> BoolEdgeMap; \ 105 typedef Graph::EdgeMap<int> IntEdgeMap; \ 106 106 typedef Graph::EdgeMap<double> DoubleEdgeMap 107 107 … … 112 112 ///\note Use this macro, if the graph type is a dependent type, 113 113 ///ie. the graph type depend on a template parameter. 114 #define TEMPLATE_GRAPH_TYPEDEFS(Graph) 115 TEMPLATE_DIGRAPH_TYPEDEFS(Graph); 116 typedef typename Graph::Edge Edge; 117 typedef typename Graph::EdgeIt EdgeIt; 118 typedef typename Graph::IncEdgeIt IncEdgeIt; 119 typedef typename Graph::template EdgeMap<bool> BoolEdgeMap; 120 typedef typename Graph::template EdgeMap<int> IntEdgeMap; 114 #define TEMPLATE_GRAPH_TYPEDEFS(Graph) \ 115 TEMPLATE_DIGRAPH_TYPEDEFS(Graph); \ 116 typedef typename Graph::Edge Edge; \ 117 typedef typename Graph::EdgeIt EdgeIt; \ 118 typedef typename Graph::IncEdgeIt IncEdgeIt; \ 119 typedef typename Graph::template EdgeMap<bool> BoolEdgeMap; \ 120 typedef typename Graph::template EdgeMap<int> IntEdgeMap; \ 121 121 typedef typename Graph::template EdgeMap<double> DoubleEdgeMap 122 122 … … 139 139 140 140 namespace _graph_utils_bits { 141 141 142 142 template <typename Graph, typename Enable = void> 143 143 struct CountNodesSelector { … … 149 149 template <typename Graph> 150 150 struct CountNodesSelector< 151 Graph, typename 152 enable_if<typename Graph::NodeNumTag, void>::type> 151 Graph, typename 152 enable_if<typename Graph::NodeNumTag, void>::type> 153 153 { 154 154 static int count(const Graph &g) { 155 155 return g.nodeNum(); 156 156 } 157 }; 157 }; 158 158 } 159 159 … … 164 164 /// graph structures it is specialized to run in O(1). 165 165 /// 166 /// If the graph contains a \e nodeNum() member function and a 166 /// If the graph contains a \e nodeNum() member function and a 167 167 /// \e NodeNumTag tag then this function calls directly the member 168 168 /// function to query the cardinality of the node set. … … 175 175 176 176 namespace _graph_utils_bits { 177 177 178 178 template <typename Graph, typename Enable = void> 179 179 struct CountArcsSelector { … … 185 185 template <typename Graph> 186 186 struct CountArcsSelector< 187 Graph, 188 typename enable_if<typename Graph::ArcNumTag, void>::type> 187 Graph, 188 typename enable_if<typename Graph::ArcNumTag, void>::type> 189 189 { 190 190 static int count(const Graph &g) { 191 191 return g.arcNum(); 192 192 } 193 }; 193 }; 194 194 } 195 195 … … 200 200 /// graph structures it is specialized to run in O(1). 201 201 /// 202 /// If the graph contains a \e arcNum() member function and a 202 /// If the graph contains a \e arcNum() member function and a 203 203 /// \e EdgeNumTag tag then this function calls directly the member 204 204 /// function to query the cardinality of the arc set. … … 210 210 // Edge counting: 211 211 namespace _graph_utils_bits { 212 212 213 213 template <typename Graph, typename Enable = void> 214 214 struct CountEdgesSelector { … … 220 220 template <typename Graph> 221 221 struct CountEdgesSelector< 222 Graph, 223 typename enable_if<typename Graph::EdgeNumTag, void>::type> 222 Graph, 223 typename enable_if<typename Graph::EdgeNumTag, void>::type> 224 224 { 225 225 static int count(const Graph &g) { 226 226 return g.edgeNum(); 227 227 } 228 }; 228 }; 229 229 } 230 230 … … 235 235 /// graph structures it is specialized to run in O(1). 236 236 /// 237 /// If the graph contains a \e edgeNum() member function and a 237 /// If the graph contains a \e edgeNum() member function and a 238 238 /// \e EdgeNumTag tag then this function calls directly the member 239 239 /// function to query the cardinality of the edge set. … … 257 257 /// 258 258 /// This function counts the number of the out-arcs from node \c n 259 /// in the graph. 259 /// in the graph. 260 260 template <typename Graph> 261 261 inline int countOutArcs(const Graph& _g, const typename Graph::Node& _n) { … … 266 266 /// 267 267 /// This function counts the number of the in-arcs to node \c n 268 /// in the graph. 268 /// in the graph. 269 269 template <typename Graph> 270 270 inline int countInArcs(const Graph& _g, const typename Graph::Node& _n) { … … 275 275 /// 276 276 /// This function counts the number of the inc-edges to node \c n 277 /// in the graph. 277 /// in the graph. 278 278 template <typename Graph> 279 279 inline int countIncEdges(const Graph& _g, const typename Graph::Node& _n) { … … 282 282 283 283 namespace _graph_utils_bits { 284 284 285 285 template <typename Graph, typename Enable = void> 286 286 struct FindArcSelector { … … 302 302 template <typename Graph> 303 303 struct FindArcSelector< 304 Graph, 305 typename enable_if<typename Graph::FindEdgeTag, void>::type> 304 Graph, 305 typename enable_if<typename Graph::FindEdgeTag, void>::type> 306 306 { 307 307 typedef typename Graph::Node Node; … … 310 310 return g.findArc(u, v, prev); 311 311 } 312 }; 312 }; 313 313 } 314 314 … … 334 334 ///\sa ConArcIt 335 335 template <typename Graph> 336 inline typename Graph::Arc 336 inline typename Graph::Arc 337 337 findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v, 338 338 typename Graph::Arc prev = INVALID) { … … 342 342 /// \brief Iterator for iterating on arcs connected the same nodes. 343 343 /// 344 /// Iterator for iterating on arcs connected the same nodes. It is 344 /// Iterator for iterating on arcs connected the same nodes. It is 345 345 /// higher level interface for the findArc() function. You can 346 346 /// use it the following way: … … 350 350 /// } 351 351 ///\endcode 352 /// 352 /// 353 353 ///\sa findArc() 354 354 ///\sa ArcLookUp … … 375 375 /// \brief Constructor. 376 376 /// 377 /// Construct a new ConArcIt which continues the iterating from 377 /// Construct a new ConArcIt which continues the iterating from 378 378 /// the \c e arc. 379 379 ConArcIt(const Graph& g, Arc a) : Parent(a), _graph(g) {} 380 380 381 381 /// \brief Increment operator. 382 382 /// 383 383 /// It increments the iterator and gives back the next arc. 384 384 ConArcIt& operator++() { 385 Parent::operator=(findArc(_graph, _graph.source(*this), 386 385 Parent::operator=(findArc(_graph, _graph.source(*this), 386 _graph.target(*this), *this)); 387 387 return *this; 388 388 } … … 392 392 393 393 namespace _graph_utils_bits { 394 394 395 395 template <typename Graph, typename Enable = void> 396 396 struct FindEdgeSelector { … … 426 426 template <typename Graph> 427 427 struct FindEdgeSelector< 428 Graph, 429 typename enable_if<typename Graph::FindEdgeTag, void>::type> 428 Graph, 429 typename enable_if<typename Graph::FindEdgeTag, void>::type> 430 430 { 431 431 typedef typename Graph::Node Node; … … 434 434 return g.findEdge(u, v, prev); 435 435 } 436 }; 436 }; 437 437 } 438 438 … … 450 450 /// Thus you can iterate through each arc from \c u to \c v as it follows. 451 451 ///\code 452 /// for(Edge e = findEdge(g,u,v); e != INVALID; 452 /// for(Edge e = findEdge(g,u,v); e != INVALID; 453 453 /// e = findEdge(g,u,v,e)) { 454 454 /// ... … … 459 459 460 460 template <typename Graph> 461 inline typename Graph::Edge 461 inline typename Graph::Edge 462 462 findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v, 463 463 typename Graph::Edge p = INVALID) { … … 467 467 /// \brief Iterator for iterating on edges connected the same nodes. 468 468 /// 469 /// Iterator for iterating on edges connected the same nodes. It is 469 /// Iterator for iterating on edges connected the same nodes. It is 470 470 /// higher level interface for the findEdge() function. You can 471 471 /// use it the following way: … … 497 497 /// \brief Constructor. 498 498 /// 499 /// Construct a new ConEdgeIt which continues the iterating from 499 /// Construct a new ConEdgeIt which continues the iterating from 500 500 /// the \c e edge. 501 501 ConEdgeIt(const Graph& g, Edge e) : Parent(e), _graph(g) {} 502 502 503 503 /// \brief Increment operator. 504 504 /// 505 505 /// It increments the iterator and gives back the next edge. 506 506 ConEdgeIt& operator++() { 507 Parent::operator=(findEdge(_graph, _graph.u(*this), 508 507 Parent::operator=(findEdge(_graph, _graph.u(*this), 508 _graph.v(*this), *this)); 509 509 return *this; 510 510 } … … 519 519 public: 520 520 virtual void copy(const Digraph& from, const RefMap& refMap) = 0; 521 521 522 522 virtual ~MapCopyBase() {} 523 523 }; 524 524 525 template <typename Digraph, typename Item, typename RefMap, 525 template <typename Digraph, typename Item, typename RefMap, 526 526 typename ToMap, typename FromMap> 527 527 class MapCopy : public MapCopyBase<Digraph, Item, RefMap> { 528 528 public: 529 529 530 MapCopy(ToMap& tmap, const FromMap& map) 530 MapCopy(ToMap& tmap, const FromMap& map) 531 531 : _tmap(tmap), _map(map) {} 532 532 533 533 virtual void copy(const Digraph& digraph, const RefMap& refMap) { 534 534 typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt; … … 548 548 549 549 ItemCopy(It& it, const Item& item) : _it(it), _item(item) {} 550 550 551 551 virtual void copy(const Digraph&, const RefMap& refMap) { 552 552 _it = refMap[_item]; … … 563 563 564 564 RefCopy(Ref& map) : _map(map) {} 565 565 566 566 virtual void copy(const Digraph& digraph, const RefMap& refMap) { 567 567 typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt; … … 575 575 }; 576 576 577 template <typename Digraph, typename Item, typename RefMap, 577 template <typename Digraph, typename Item, typename RefMap, 578 578 typename CrossRef> 579 579 class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> { … … 581 581 582 582 CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {} 583 583 584 584 virtual void copy(const Digraph& digraph, const RefMap& refMap) { 585 585 typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt; … … 602 602 } 603 603 for (typename From::ArcIt it(from); it != INVALID; ++it) { 604 arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)], 605 604 arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)], 605 nodeRefMap[from.target(it)]); 606 606 } 607 607 } … … 610 610 template <typename Digraph> 611 611 struct DigraphCopySelector< 612 Digraph, 613 typename enable_if<typename Digraph::BuildTag, void>::type> 612 Digraph, 613 typename enable_if<typename Digraph::BuildTag, void>::type> 614 614 { 615 615 template <typename From, typename NodeRefMap, typename ArcRefMap> … … 629 629 } 630 630 for (typename From::EdgeIt it(from); it != INVALID; ++it) { 631 edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)], 632 631 edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)], 632 nodeRefMap[from.v(it)]); 633 633 } 634 634 } … … 637 637 template <typename Graph> 638 638 struct GraphCopySelector< 639 Graph, 640 typename enable_if<typename Graph::BuildTag, void>::type> 639 Graph, 640 typename enable_if<typename Graph::BuildTag, void>::type> 641 641 { 642 642 template <typename From, typename NodeRefMap, typename EdgeRefMap> … … 698 698 typedef typename From::template NodeMap<TNode> NodeRefMap; 699 699 typedef typename From::template ArcMap<TArc> ArcRefMap; 700 701 702 public: 700 701 702 public: 703 703 704 704 … … 707 707 /// It copies the content of the \c _from digraph into the 708 708 /// \c _to digraph. 709 DigraphCopy(To& to, const From& from) 709 DigraphCopy(To& to, const From& from) 710 710 : _from(from), _to(to) {} 711 711 … … 731 731 template <typename NodeRef> 732 732 DigraphCopy& nodeRef(NodeRef& map) { 733 _node_maps.push_back(new _graph_utils_bits::RefCopy<From, Node, 734 733 _node_maps.push_back(new _graph_utils_bits::RefCopy<From, Node, 734 NodeRefMap, NodeRef>(map)); 735 735 return *this; 736 736 } … … 745 745 DigraphCopy& nodeCrossRef(NodeCrossRef& map) { 746 746 _node_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Node, 747 747 NodeRefMap, NodeCrossRef>(map)); 748 748 return *this; 749 749 } … … 756 756 template <typename ToMap, typename FromMap> 757 757 DigraphCopy& nodeMap(ToMap& tmap, const FromMap& map) { 758 _node_maps.push_back(new _graph_utils_bits::MapCopy<From, Node, 759 758 _node_maps.push_back(new _graph_utils_bits::MapCopy<From, Node, 759 NodeRefMap, ToMap, FromMap>(tmap, map)); 760 760 return *this; 761 761 } … … 765 765 /// Make a copy of the given node. 766 766 DigraphCopy& node(TNode& tnode, const Node& snode) { 767 _node_maps.push_back(new _graph_utils_bits::ItemCopy<From, Node, 768 767 _node_maps.push_back(new _graph_utils_bits::ItemCopy<From, Node, 768 NodeRefMap, TNode>(tnode, snode)); 769 769 return *this; 770 770 } … … 775 775 template <typename ArcRef> 776 776 DigraphCopy& arcRef(ArcRef& map) { 777 _arc_maps.push_back(new _graph_utils_bits::RefCopy<From, Arc, 778 777 _arc_maps.push_back(new _graph_utils_bits::RefCopy<From, Arc, 778 ArcRefMap, ArcRef>(map)); 779 779 return *this; 780 780 } … … 787 787 DigraphCopy& arcCrossRef(ArcCrossRef& map) { 788 788 _arc_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Arc, 789 789 ArcRefMap, ArcCrossRef>(map)); 790 790 return *this; 791 791 } … … 793 793 /// \brief Make copy of the given map. 794 794 /// 795 /// Makes copy of the given map for the newly created digraph. 795 /// Makes copy of the given map for the newly created digraph. 796 796 /// The new map's key type is the to digraph's arc type, 797 797 /// and the copied map's key type is the from digraph's arc 798 /// type. 798 /// type. 799 799 template <typename ToMap, typename FromMap> 800 800 DigraphCopy& arcMap(ToMap& tmap, const FromMap& map) { 801 _arc_maps.push_back(new _graph_utils_bits::MapCopy<From, Arc, 802 801 _arc_maps.push_back(new _graph_utils_bits::MapCopy<From, Arc, 802 ArcRefMap, ToMap, FromMap>(tmap, map)); 803 803 return *this; 804 804 } … … 808 808 /// Make a copy of the given arc. 809 809 DigraphCopy& arc(TArc& tarc, const Arc& sarc) { 810 _arc_maps.push_back(new _graph_utils_bits::ItemCopy<From, Arc, 811 810 _arc_maps.push_back(new _graph_utils_bits::ItemCopy<From, Arc, 811 ArcRefMap, TArc>(tarc, sarc)); 812 812 return *this; 813 813 } … … 826 826 for (int i = 0; i < int(_arc_maps.size()); ++i) { 827 827 _arc_maps[i]->copy(_from, arcRefMap); 828 } 828 } 829 829 } 830 830 … … 835 835 To& _to; 836 836 837 std::vector<_graph_utils_bits::MapCopyBase<From, Node, NodeRefMap>* > 837 std::vector<_graph_utils_bits::MapCopyBase<From, Node, NodeRefMap>* > 838 838 _node_maps; 839 839 840 std::vector<_graph_utils_bits::MapCopyBase<From, Arc, ArcRefMap>* > 840 std::vector<_graph_utils_bits::MapCopyBase<From, Arc, ArcRefMap>* > 841 841 _arc_maps; 842 842 … … 851 851 /// copyDigraph(trg, src).nodeRef(nr).arcCrossRef(ecr).run(); 852 852 ///\endcode 853 /// 853 /// 854 854 /// After the copy the \c nr map will contain the mapping from the 855 855 /// nodes of the \c from digraph to the nodes of the \c to digraph and … … 857 857 /// to the arcs of the \c from digraph. 858 858 /// 859 /// \see DigraphCopy 859 /// \see DigraphCopy 860 860 template <typename To, typename From> 861 861 DigraphCopy<To, From> copyDigraph(To& to, const From& from) { … … 918 918 struct ArcRefMap { 919 919 ArcRefMap(const To& to, const From& from, 920 const EdgeRefMap& edge_ref, const NodeRefMap& node_ref) 921 : _to(to), _from(from), 920 const EdgeRefMap& edge_ref, const NodeRefMap& node_ref) 921 : _to(to), _from(from), 922 922 _edge_ref(edge_ref), _node_ref(node_ref) {} 923 923 … … 927 927 Value operator[](const Key& key) const { 928 928 bool forward = _from.u(key) != _from.v(key) ? 929 _node_ref[_from.source(key)] == 930 931 932 return _to.direct(_edge_ref[key], forward); 933 } 934 929 _node_ref[_from.source(key)] == 930 _to.source(_to.direct(_edge_ref[key], true)) : 931 _from.direction(key); 932 return _to.direct(_edge_ref[key], forward); 933 } 934 935 935 const To& _to; 936 936 const From& _from; … … 939 939 }; 940 940 941 942 public: 941 942 public: 943 943 944 944 … … 947 947 /// It copies the content of the \c _from graph into the 948 948 /// \c _to graph. 949 GraphCopy(To& to, const From& from) 949 GraphCopy(To& to, const From& from) 950 950 : _from(from), _to(to) {} 951 951 … … 971 971 template <typename NodeRef> 972 972 GraphCopy& nodeRef(NodeRef& map) { 973 _node_maps.push_back(new _graph_utils_bits::RefCopy<From, Node, 974 973 _node_maps.push_back(new _graph_utils_bits::RefCopy<From, Node, 974 NodeRefMap, NodeRef>(map)); 975 975 return *this; 976 976 } … … 983 983 GraphCopy& nodeCrossRef(NodeCrossRef& map) { 984 984 _node_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Node, 985 985 NodeRefMap, NodeCrossRef>(map)); 986 986 return *this; 987 987 } … … 989 989 /// \brief Make copy of the given map. 990 990 /// 991 /// Makes copy of the given map for the newly created graph. 991 /// Makes copy of the given map for the newly created graph. 992 992 /// The new map's key type is the to graph's node type, 993 993 /// and the copied map's key type is the from graph's node 994 /// type. 994 /// type. 995 995 template <typename ToMap, typename FromMap> 996 996 GraphCopy& nodeMap(ToMap& tmap, const FromMap& map) { 997 _node_maps.push_back(new _graph_utils_bits::MapCopy<From, Node, 998 997 _node_maps.push_back(new _graph_utils_bits::MapCopy<From, Node, 998 NodeRefMap, ToMap, FromMap>(tmap, map)); 999 999 return *this; 1000 1000 } … … 1004 1004 /// Make a copy of the given node. 1005 1005 GraphCopy& node(TNode& tnode, const Node& snode) { 1006 _node_maps.push_back(new _graph_utils_bits::ItemCopy<From, Node, 1007 1006 _node_maps.push_back(new _graph_utils_bits::ItemCopy<From, Node, 1007 NodeRefMap, TNode>(tnode, snode)); 1008 1008 return *this; 1009 1009 } … … 1014 1014 template <typename ArcRef> 1015 1015 GraphCopy& arcRef(ArcRef& map) { 1016 _arc_maps.push_back(new _graph_utils_bits::RefCopy<From, Arc, 1017 1016 _arc_maps.push_back(new _graph_utils_bits::RefCopy<From, Arc, 1017 ArcRefMap, ArcRef>(map)); 1018 1018 return *this; 1019 1019 } … … 1026 1026 GraphCopy& arcCrossRef(ArcCrossRef& map) { 1027 1027 _arc_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, Arc, 1028 1028 ArcRefMap, ArcCrossRef>(map)); 1029 1029 return *this; 1030 1030 } … … 1032 1032 /// \brief Make copy of the given map. 1033 1033 /// 1034 /// Makes copy of the given map for the newly created graph. 1034 /// Makes copy of the given map for the newly created graph. 1035 1035 /// The new map's key type is the to graph's arc type, 1036 1036 /// and the copied map's key type is the from graph's arc 1037 /// type. 1037 /// type. 1038 1038 template <typename ToMap, typename FromMap> 1039 1039 GraphCopy& arcMap(ToMap& tmap, const FromMap& map) { 1040 _arc_maps.push_back(new _graph_utils_bits::MapCopy<From, Arc, 1041 1040 _arc_maps.push_back(new _graph_utils_bits::MapCopy<From, Arc, 1041 ArcRefMap, ToMap, FromMap>(tmap, map)); 1042 1042 return *this; 1043 1043 } … … 1047 1047 /// Make a copy of the given arc. 1048 1048 GraphCopy& arc(TArc& tarc, const Arc& sarc) { 1049 _arc_maps.push_back(new _graph_utils_bits::ItemCopy<From, Arc, 1050 1049 _arc_maps.push_back(new _graph_utils_bits::ItemCopy<From, Arc, 1050 ArcRefMap, TArc>(tarc, sarc)); 1051 1051 return *this; 1052 1052 } … … 1057 1057 template <typename EdgeRef> 1058 1058 GraphCopy& edgeRef(EdgeRef& map) { 1059 _edge_maps.push_back(new _graph_utils_bits::RefCopy<From, Edge, 1060 1059 _edge_maps.push_back(new _graph_utils_bits::RefCopy<From, Edge, 1060 EdgeRefMap, EdgeRef>(map)); 1061 1061 return *this; 1062 1062 } … … 1068 1068 template <typename EdgeCrossRef> 1069 1069 GraphCopy& edgeCrossRef(EdgeCrossRef& map) { 1070 _edge_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, 1071 1070 _edge_maps.push_back(new _graph_utils_bits::CrossRefCopy<From, 1071 Edge, EdgeRefMap, EdgeCrossRef>(map)); 1072 1072 return *this; 1073 1073 } … … 1075 1075 /// \brief Make copy of the given map. 1076 1076 /// 1077 /// Makes copy of the given map for the newly created graph. 1077 /// Makes copy of the given map for the newly created graph. 1078 1078 /// The new map's key type is the to graph's edge type, 1079 1079 /// and the copied map's key type is the from graph's edge 1080 /// type. 1080 /// type. 1081 1081 template <typename ToMap, typename FromMap> 1082 1082 GraphCopy& edgeMap(ToMap& tmap, const FromMap& map) { 1083 _edge_maps.push_back(new _graph_utils_bits::MapCopy<From, Edge, 1084 1083 _edge_maps.push_back(new _graph_utils_bits::MapCopy<From, Edge, 1084 EdgeRefMap, ToMap, FromMap>(tmap, map)); 1085 1085 return *this; 1086 1086 } … … 1090 1090 /// Make a copy of the given edge. 1091 1091 GraphCopy& edge(TEdge& tedge, const Edge& sedge) { 1092 _edge_maps.push_back(new _graph_utils_bits::ItemCopy<From, Edge, 1093 1092 _edge_maps.push_back(new _graph_utils_bits::ItemCopy<From, Edge, 1093 EdgeRefMap, TEdge>(tedge, sedge)); 1094 1094 return *this; 1095 1095 } … … 1116 1116 1117 1117 private: 1118 1118 1119 1119 const From& _from; 1120 1120 To& _to; 1121 1121 1122 std::vector<_graph_utils_bits::MapCopyBase<From, Node, NodeRefMap>* > 1122 std::vector<_graph_utils_bits::MapCopyBase<From, Node, NodeRefMap>* > 1123 1123 _node_maps; 1124 1124 1125 std::vector<_graph_utils_bits::MapCopyBase<From, Arc, ArcRefMap>* > 1125 std::vector<_graph_utils_bits::MapCopyBase<From, Arc, ArcRefMap>* > 1126 1126 _arc_maps; 1127 1127 1128 std::vector<_graph_utils_bits::MapCopyBase<From, Edge, EdgeRefMap>* > 1128 std::vector<_graph_utils_bits::MapCopyBase<From, Edge, EdgeRefMap>* > 1129 1129 _edge_maps; 1130 1130 … … 1139 1139 /// copyGraph(trg, src).nodeRef(nr).arcCrossRef(ecr).run(); 1140 1140 ///\endcode 1141 /// 1141 /// 1142 1142 /// After the copy the \c nr map will contain the mapping from the 1143 1143 /// nodes of the \c from graph to the nodes of the \c to graph and … … 1145 1145 /// to the arcs of the \c from graph. 1146 1146 /// 1147 /// \see GraphCopy 1147 /// \see GraphCopy 1148 1148 template <typename To, typename From> 1149 GraphCopy<To, From> 1149 GraphCopy<To, From> 1150 1150 copyGraph(To& to, const From& from) { 1151 1151 return GraphCopy<To, From>(to, from); … … 1215 1215 /// 1216 1216 /// Gives back the given item from its id. 1217 /// 1217 /// 1218 1218 Item operator[](int id) const { return _graph->fromId(id, Item());} 1219 1219 … … 1225 1225 /// 1226 1226 /// Gives back the inverse of the IdMap. 1227 InverseMap inverse() const { return InverseMap(*_graph);} 1227 InverseMap inverse() const { return InverseMap(*_graph);} 1228 1228 1229 1229 }; 1230 1230 1231 1231 1232 1232 /// \brief General invertable graph-map type. 1233 1233 1234 /// This type provides simple invertable graph-maps. 1235 /// The InvertableMap wraps an arbitrary ReadWriteMap 1234 /// This type provides simple invertable graph-maps. 1235 /// The InvertableMap wraps an arbitrary ReadWriteMap 1236 1236 /// and if a key is set to a new value then store it 1237 1237 /// in the inverse map. … … 1248 1248 class InvertableMap : protected DefaultMap<_Graph, _Item, _Value> { 1249 1249 private: 1250 1250 1251 1251 typedef DefaultMap<_Graph, _Item, _Value> Map; 1252 1252 typedef _Graph Graph; 1253 1253 1254 1254 typedef std::map<_Value, _Item> Container; 1255 Container _inv_map; 1255 Container _inv_map; 1256 1256 1257 1257 public: 1258 1258 1259 1259 /// The key type of InvertableMap (Node, Arc, Edge). 1260 1260 typedef typename Map::Key Key; … … 1268 1268 /// Construct a new InvertableMap for the graph. 1269 1269 /// 1270 explicit InvertableMap(const Graph& graph) : Map(graph) {} 1270 explicit InvertableMap(const Graph& graph) : Map(graph) {} 1271 1271 1272 1272 /// \brief Forward iterator for values. … … 1276 1276 /// be accessed in the [beginValue, endValue) range. 1277 1277 /// 1278 class ValueIterator 1278 class ValueIterator 1279 1279 : public std::iterator<std::forward_iterator_tag, Value> { 1280 1280 friend class InvertableMap; 1281 1281 private: 1282 ValueIterator(typename Container::const_iterator _it) 1282 ValueIterator(typename Container::const_iterator _it) 1283 1283 : it(_it) {} 1284 1284 public: 1285 1285 1286 1286 ValueIterator() {} 1287 1287 1288 1288 ValueIterator& operator++() { ++it; return *this; } 1289 ValueIterator operator++(int) { 1290 ValueIterator tmp(*this); 1289 ValueIterator operator++(int) { 1290 ValueIterator tmp(*this); 1291 1291 operator++(); 1292 return tmp; 1292 return tmp; 1293 1293 } 1294 1294 … … 1298 1298 bool operator==(ValueIterator jt) const { return it == jt.it; } 1299 1299 bool operator!=(ValueIterator jt) const { return it != jt.it; } 1300 1300 1301 1301 private: 1302 1302 typename Container::const_iterator it; … … 1305 1305 /// \brief Returns an iterator to the first value. 1306 1306 /// 1307 /// Returns an stl compatible iterator to the 1307 /// Returns an stl compatible iterator to the 1308 1308 /// first value of the map. The values of the 1309 1309 /// map can be accessed in the [beginValue, endValue) … … 1315 1315 /// \brief Returns an iterator after the last value. 1316 1316 /// 1317 /// Returns an stl compatible iterator after the 1317 /// Returns an stl compatible iterator after the 1318 1318 /// last value of the map. The values of the 1319 1319 /// map can be accessed in the [beginValue, endValue) … … 1322 1322 return ValueIterator(_inv_map.end()); 1323 1323 } 1324 1324 1325 1325 /// \brief The setter function of the map. 1326 1326 /// … … 1330 1330 typename Container::iterator it = _inv_map.find(oldval); 1331 1331 if (it != _inv_map.end() && it->second == key) { 1332 1333 } 1332 _inv_map.erase(it); 1333 } 1334 1334 _inv_map.insert(make_pair(val, key)); 1335 1335 Map::set(key, val); … … 1339 1339 /// 1340 1340 /// It gives back the value associated with the key. 1341 typename MapTraits<Map>::ConstReturnValue 1341 typename MapTraits<Map>::ConstReturnValue 1342 1342 operator[](const Key& key) const { 1343 1343 return Map::operator[](key); … … 1362 1362 typename Container::iterator it = _inv_map.find(val); 1363 1363 if (it != _inv_map.end() && it->second == key) { 1364 1364 _inv_map.erase(it); 1365 1365 } 1366 1366 Map::erase(key); … … 1373 1373 virtual void erase(const std::vector<Key>& keys) { 1374 1374 for (int i = 0; i < int(keys.size()); ++i) { 1375 1376 1377 1378 1379 1375 Value val = Map::operator[](keys[i]); 1376 typename Container::iterator it = _inv_map.find(val); 1377 if (it != _inv_map.end() && it->second == keys[i]) { 1378 _inv_map.erase(it); 1379 } 1380 1380 } 1381 1381 Map::erase(keys); … … 1396 1396 /// 1397 1397 /// The inverse of this map. The subscript operator of the map 1398 /// gives back always the item what was last assigned to the value. 1398 /// gives back always the item what was last assigned to the value. 1399 1399 class InverseMap { 1400 1400 public: … … 1402 1402 /// 1403 1403 /// Constructor of the InverseMap. 1404 explicit InverseMap(const InvertableMap& inverted) 1404 explicit InverseMap(const InvertableMap& inverted) 1405 1405 : _inverted(inverted) {} 1406 1406 … … 1408 1408 typedef typename InvertableMap::Key Value; 1409 1409 /// The key type of the InverseMap. 1410 typedef typename InvertableMap::Value Key; 1411 1412 /// \brief Subscript operator. 1410 typedef typename InvertableMap::Value Key; 1411 1412 /// \brief Subscript operator. 1413 1413 /// 1414 /// Subscript operator. It gives back always the item 1414 /// Subscript operator. It gives back always the item 1415 1415 /// what was last assigned to the value. 1416 1416 Value operator[](const Key& key) const { 1417 1418 } 1419 1417 return _inverted(key); 1418 } 1419 1420 1420 private: 1421 1421 const InvertableMap& _inverted; … … 1427 1427 InverseMap inverse() const { 1428 1428 return InverseMap(*this); 1429 } 1430 1431 1432 1429 } 1430 1431 1432 1433 1433 }; 1434 1434 1435 /// \brief Provides a mutable, continuous and unique descriptor for each 1435 /// \brief Provides a mutable, continuous and unique descriptor for each 1436 1436 /// item in the graph. 1437 1437 /// … … 1446 1446 /// 1447 1447 /// \tparam _Graph The graph class the \c DescriptorMap belongs to. 1448 /// \tparam _Item The Item is the Key of the Map. It may be Node, Arc or 1448 /// \tparam _Item The Item is the Key of the Map. It may be Node, Arc or 1449 1449 /// Edge. 1450 1450 template <typename _Graph, typename _Item> … … 1468 1468 explicit DescriptorMap(const Graph& _graph) : Map(_graph) { 1469 1469 Item it; 1470 const typename Map::Notifier* nf = Map::notifier(); 1470 const typename Map::Notifier* nf = Map::notifier(); 1471 1471 for (nf->first(it); it != INVALID; nf->next(it)) { 1472 1473 _inv_map.push_back(it); 1474 } 1472 Map::set(it, _inv_map.size()); 1473 _inv_map.push_back(it); 1474 } 1475 1475 } 1476 1476 … … 1494 1494 Map::add(items); 1495 1495 for (int i = 0; i < int(items.size()); ++i) { 1496 1497 1496 Map::set(items[i], _inv_map.size()); 1497 _inv_map.push_back(items[i]); 1498 1498 } 1499 1499 } … … 1516 1516 virtual void erase(const std::vector<Item>& items) { 1517 1517 for (int i = 0; i < int(items.size()); ++i) { 1518 1519 1520 1518 Map::set(_inv_map.back(), Map::operator[](items[i])); 1519 _inv_map[Map::operator[](items[i])] = _inv_map.back(); 1520 _inv_map.pop_back(); 1521 1521 } 1522 1522 Map::erase(items); … … 1530 1530 Map::build(); 1531 1531 Item it; 1532 const typename Map::Notifier* nf = Map::notifier(); 1532 const typename Map::Notifier* nf = Map::notifier(); 1533 1533 for (nf->first(it); it != INVALID; nf->next(it)) { 1534 1535 _inv_map.push_back(it); 1536 } 1537 } 1538 1534 Map::set(it, _inv_map.size()); 1535 _inv_map.push_back(it); 1536 } 1537 } 1538 1539 1539 /// \brief Clear the keys from the map. 1540 1540 /// … … 1580 1580 return _inv_map[id]; 1581 1581 } 1582 1582 1583 1583 private: 1584 1584 … … 1595 1595 /// 1596 1596 /// Constructor of the InverseMap. 1597 explicit InverseMap(const DescriptorMap& inverted) 1598 1597 explicit InverseMap(const DescriptorMap& inverted) 1598 : _inverted(inverted) {} 1599 1599 1600 1600 … … 1602 1602 typedef typename DescriptorMap::Key Value; 1603 1603 /// The key type of the InverseMap. 1604 typedef typename DescriptorMap::Value Key; 1605 1606 /// \brief Subscript operator. 1604 typedef typename DescriptorMap::Value Key; 1605 1606 /// \brief Subscript operator. 1607 1607 /// 1608 /// Subscript operator. It gives back the item 1608 /// Subscript operator. It gives back the item 1609 1609 /// that the descriptor belongs to currently. 1610 1610 Value operator[](const Key& key) const { 1611 1611 return _inverted(key); 1612 1612 } 1613 1613 … … 1616 1616 /// Returns the size of the map. 1617 1617 unsigned int size() const { 1618 1619 } 1620 1618 return _inverted.size(); 1619 } 1620 1621 1621 private: 1622 1622 const DescriptorMap& _inverted; … … 1633 1633 /// \brief Returns the source of the given arc. 1634 1634 /// 1635 /// The SourceMap gives back the source Node of the given arc. 1635 /// The SourceMap gives back the source Node of the given arc. 1636 1636 /// \see TargetMap 1637 1637 template <typename Digraph> … … 1651 1651 /// 1652 1652 /// The subscript operator. 1653 /// \param arc The arc 1654 /// \return The source of the arc 1653 /// \param arc The arc 1654 /// \return The source of the arc 1655 1655 Value operator[](const Key& arc) const { 1656 1656 return _digraph.source(arc); … … 1668 1668 inline SourceMap<Digraph> sourceMap(const Digraph& digraph) { 1669 1669 return SourceMap<Digraph>(digraph); 1670 } 1670 } 1671 1671 1672 1672 /// \brief Returns the target of the given arc. 1673 1673 /// 1674 /// The TargetMap gives back the target Node of the given arc. 1674 /// The TargetMap gives back the target Node of the given arc. 1675 1675 /// \see SourceMap 1676 1676 template <typename Digraph> … … 1690 1690 /// 1691 1691 /// The subscript operator. 1692 /// \param e The arc 1693 /// \return The target of the arc 1692 /// \param e The arc 1693 /// \return The target of the arc 1694 1694 Value operator[](const Key& e) const { 1695 1695 return _digraph.target(e); … … 1729 1729 /// 1730 1730 /// The subscript operator. 1731 /// \param key An edge 1732 /// \return The "forward" directed arc view of edge 1731 /// \param key An edge 1732 /// \return The "forward" directed arc view of edge 1733 1733 Value operator[](const Key& key) const { 1734 1734 return _graph.direct(key, true); … … 1768 1768 /// 1769 1769 /// The subscript operator. 1770 /// \param key An edge 1771 /// \return The "backward" directed arc view of edge 1770 /// \param key An edge 1771 /// \return The "backward" directed arc view of edge 1772 1772 Value operator[](const Key& key) const { 1773 1773 return _graph.direct(key, false); … … 1801 1801 /// 1802 1802 /// Contructor of the map 1803 explicit PotentialDifferenceMap(const Digraph& digraph, 1804 const NodeMap& potential) 1803 explicit PotentialDifferenceMap(const Digraph& digraph, 1804 const NodeMap& potential) 1805 1805 : _digraph(digraph), _potential(potential) {} 1806 1806 … … 1809 1809 /// Const subscription operator 1810 1810 Value operator[](const Key& arc) const { 1811 return _potential[_digraph.target(arc)] - 1812 1811 return _potential[_digraph.target(arc)] - 1812 _potential[_digraph.source(arc)]; 1813 1813 } 1814 1814 … … 1823 1823 /// \relates PotentialDifferenceMap 1824 1824 template <typename Digraph, typename NodeMap> 1825 PotentialDifferenceMap<Digraph, NodeMap> 1825 PotentialDifferenceMap<Digraph, NodeMap> 1826 1826 potentialDifferenceMap(const Digraph& digraph, const NodeMap& potential) { 1827 1827 return PotentialDifferenceMap<Digraph, NodeMap>(digraph, potential); … … 1846 1846 1847 1847 template <typename _Digraph> 1848 class InDegMap 1848 class InDegMap 1849 1849 : protected ItemSetTraits<_Digraph, typename _Digraph::Arc> 1850 1850 ::ItemNotifier::ObserverBase { 1851 1851 1852 1852 public: 1853 1853 1854 1854 typedef _Digraph Digraph; 1855 1855 typedef int Value; … … 1867 1867 1868 1868 AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {} 1869 1869 1870 1870 virtual void add(const Key& key) { 1871 1872 1871 Parent::add(key); 1872 Parent::set(key, 0); 1873 1873 } 1874 1874 1875 1875 virtual void add(const std::vector<Key>& keys) { 1876 1877 1878 1879 1876 Parent::add(keys); 1877 for (int i = 0; i < int(keys.size()); ++i) { 1878 Parent::set(keys[i], 0); 1879 } 1880 1880 } 1881 1881 1882 1882 virtual void build() { 1883 1884 1885 1886 1887 1888 1883 Parent::build(); 1884 Key it; 1885 typename Parent::Notifier* nf = Parent::notifier(); 1886 for (nf->first(it); it != INVALID; nf->next(it)) { 1887 Parent::set(it, 0); 1888 } 1889 1889 } 1890 1890 }; … … 1895 1895 /// 1896 1896 /// Constructor for creating in-degree map. 1897 explicit InDegMap(const Digraph& digraph) 1897 explicit InDegMap(const Digraph& digraph) 1898 1898 : _digraph(digraph), _deg(digraph) { 1899 1899 Parent::attach(_digraph.notifier(typename Digraph::Arc())); 1900 1900 1901 1901 for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) { 1902 1903 } 1904 } 1905 1902 _deg[it] = countInArcs(_digraph, it); 1903 } 1904 } 1905 1906 1906 /// Gives back the in-degree of a Node. 1907 1907 int operator[](const Key& key) const { … … 1910 1910 1911 1911 protected: 1912 1912 1913 1913 typedef typename Digraph::Arc Arc; 1914 1914 … … 1935 1935 virtual void build() { 1936 1936 for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) { 1937 1938 } 1937 _deg[it] = countInArcs(_digraph, it); 1938 } 1939 1939 } 1940 1940 1941 1941 virtual void clear() { 1942 1942 for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) { 1943 1943 _deg[it] = 0; 1944 1944 } 1945 1945 } 1946 1946 private: 1947 1947 1948 1948 const Digraph& _digraph; 1949 1949 AutoNodeMap _deg; … … 1968 1968 1969 1969 template <typename _Digraph> 1970 class OutDegMap 1970 class OutDegMap 1971 1971 : protected ItemSetTraits<_Digraph, typename _Digraph::Arc> 1972 1972 ::ItemNotifier::ObserverBase { 1973 1973 1974 1974 public: 1975 1975 1976 1976 typedef _Digraph Digraph; 1977 1977 typedef int Value; … … 1989 1989 1990 1990 AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {} 1991 1991 1992 1992 virtual void add(const Key& key) { 1993 1994 1993 Parent::add(key); 1994 Parent::set(key, 0); 1995 1995 } 1996 1996 virtual void add(const std::vector<Key>& keys) { 1997 1998 1999 2000 1997 Parent::add(keys); 1998 for (int i = 0; i < int(keys.size()); ++i) { 1999 Parent::set(keys[i], 0); 2000 } 2001 2001 } 2002 2002 virtual void build() { 2003 2004 2005 2006 2007 2008 2003 Parent::build(); 2004 Key it; 2005 typename Parent::Notifier* nf = Parent::notifier(); 2006 for (nf->first(it); it != INVALID; nf->next(it)) { 2007 Parent::set(it, 0); 2008 } 2009 2009 } 2010 2010 }; … … 2015 2015 /// 2016 2016 /// Constructor for creating out-degree map. 2017 explicit OutDegMap(const Digraph& digraph) 2017 explicit OutDegMap(const Digraph& digraph) 2018 2018 : _digraph(digraph), _deg(digraph) { 2019 2019 Parent::attach(_digraph.notifier(typename Digraph::Arc())); 2020 2020 2021 2021 for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) { 2022 2022 _deg[it] = countOutArcs(_digraph, it); 2023 2023 } 2024 2024 } … … 2030 2030 2031 2031 protected: 2032 2032 2033 2033 typedef typename Digraph::Arc Arc; 2034 2034 … … 2055 2055 virtual void build() { 2056 2056 for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) { 2057 2058 } 2057 _deg[it] = countOutArcs(_digraph, it); 2058 } 2059 2059 } 2060 2060 2061 2061 virtual void clear() { 2062 2062 for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) { 2063 2063 _deg[it] = 0; 2064 2064 } 2065 2065 } 2066 2066 private: 2067 2067 2068 2068 const Digraph& _digraph; 2069 2069 AutoNodeMap _deg; … … 2072 2072 2073 2073 ///Dynamic arc look up between given endpoints. 2074 2074 2075 2075 ///\ingroup gutils 2076 2076 ///Using this class, you can find an arc in a digraph from a given … … 2090 2090 ///queries. 2091 2091 /// 2092 ///\tparam G The type of the underlying digraph. 2093 /// 2094 ///\sa ArcLookUp 2095 ///\sa AllArcLookUp 2092 ///\tparam G The type of the underlying digraph. 2093 /// 2094 ///\sa ArcLookUp 2095 ///\sa AllArcLookUp 2096 2096 template<class G> 2097 class DynArcLookUp 2097 class DynArcLookUp 2098 2098 : protected ItemSetTraits<G, typename G::Arc>::ItemNotifier::ObserverBase 2099 2099 { … … 2113 2113 2114 2114 AutoNodeMap(const G& digraph) : Parent(digraph, INVALID) {} 2115 2115 2116 2116 virtual void add(const Node& node) { 2117 2118 2117 Parent::add(node); 2118 Parent::set(node, INVALID); 2119 2119 } 2120 2120 2121 2121 virtual void add(const std::vector<Node>& nodes) { 2122 2123 2124 2125 2122 Parent::add(nodes); 2123 for (int i = 0; i < int(nodes.size()); ++i) { 2124 Parent::set(nodes[i], INVALID); 2125 } 2126 2126 } 2127 2127 2128 2128 virtual void build() { 2129 2130 2131 2132 2133 2134 2129 Parent::build(); 2130 Node it; 2131 typename Parent::Notifier* nf = Parent::notifier(); 2132 for (nf->first(it); it != INVALID; nf->next(it)) { 2133 Parent::set(it, INVALID); 2134 } 2135 2135 } 2136 2136 }; … … 2141 2141 typename Digraph::template ArcMap<Arc> _left; 2142 2142 typename Digraph::template ArcMap<Arc> _right; 2143 2143 2144 2144 class ArcLess { 2145 2145 const Digraph &g; 2146 2146 public: 2147 2147 ArcLess(const Digraph &_g) : g(_g) {} 2148 bool operator()(Arc a,Arc b) const 2148 bool operator()(Arc a,Arc b) const 2149 2149 { 2150 2151 } 2152 }; 2153 2150 return g.target(a)<g.target(b); 2151 } 2152 }; 2153 2154 2154 public: 2155 2155 2156 2156 ///Constructor 2157 2157 … … 2159 2159 /// 2160 2160 ///It builds up the search database. 2161 DynArcLookUp(const Digraph &g) 2162 : _g(g),_head(g),_parent(g),_left(g),_right(g) 2163 { 2161 DynArcLookUp(const Digraph &g) 2162 : _g(g),_head(g),_parent(g),_left(g),_right(g) 2163 { 2164 2164 Parent::attach(_g.notifier(typename Digraph::Arc())); 2165 refresh(); 2166 } 2167 2165 refresh(); 2166 } 2167 2168 2168 protected: 2169 2169 … … 2174 2174 virtual void add(const std::vector<Arc>& arcs) { 2175 2175 for (int i = 0; i < int(arcs.size()); ++i) { 2176 2176 insert(arcs[i]); 2177 2177 } 2178 2178 } … … 2184 2184 virtual void erase(const std::vector<Arc>& arcs) { 2185 2185 for (int i = 0; i < int(arcs.size()); ++i) { 2186 2187 } 2186 remove(arcs[i]); 2187 } 2188 2188 } 2189 2189 … … 2194 2194 virtual void clear() { 2195 2195 for(NodeIt n(_g);n!=INVALID;++n) { 2196 2196 _head.set(n, INVALID); 2197 2197 } 2198 2198 } … … 2203 2203 _left.set(arc, INVALID); 2204 2204 _right.set(arc, INVALID); 2205 2205 2206 2206 Arc e = _head[s]; 2207 2207 if (e == INVALID) { 2208 2209 2210 2208 _head.set(s, arc); 2209 _parent.set(arc, INVALID); 2210 return; 2211 2211 } 2212 2212 while (true) { 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2213 if (t < _g.target(e)) { 2214 if (_left[e] == INVALID) { 2215 _left.set(e, arc); 2216 _parent.set(arc, e); 2217 splay(arc); 2218 return; 2219 } else { 2220 e = _left[e]; 2221 } 2222 } else { 2223 if (_right[e] == INVALID) { 2224 _right.set(e, arc); 2225 _parent.set(arc, e); 2226 splay(arc); 2227 return; 2228 } else { 2229 e = _right[e]; 2230 } 2231 } 2232 2232 } 2233 2233 } … … 2235 2235 void remove(Arc arc) { 2236 2236 if (_left[arc] == INVALID) { 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2237 if (_right[arc] != INVALID) { 2238 _parent.set(_right[arc], _parent[arc]); 2239 } 2240 if (_parent[arc] != INVALID) { 2241 if (_left[_parent[arc]] == arc) { 2242 _left.set(_parent[arc], _right[arc]); 2243 } else { 2244 _right.set(_parent[arc], _right[arc]); 2245 } 2246 } else { 2247 _head.set(_g.source(arc), _right[arc]); 2248 } 2249 2249 } else if (_right[arc] == INVALID) { 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2250 _parent.set(_left[arc], _parent[arc]); 2251 if (_parent[arc] != INVALID) { 2252 if (_left[_parent[arc]] == arc) { 2253 _left.set(_parent[arc], _left[arc]); 2254 } else { 2255 _right.set(_parent[arc], _left[arc]); 2256 } 2257 } else { 2258 _head.set(_g.source(arc), _left[arc]); 2259 } 2260 2260 } else { 2261 2262 2263 e = _right[e]; 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 } 2302 } 2303 2304 Arc refreshRec(std::vector<Arc> &v,int a,int b) 2261 Arc e = _left[arc]; 2262 if (_right[e] != INVALID) { 2263 e = _right[e]; 2264 while (_right[e] != INVALID) { 2265 e = _right[e]; 2266 } 2267 Arc s = _parent[e]; 2268 _right.set(_parent[e], _left[e]); 2269 if (_left[e] != INVALID) { 2270 _parent.set(_left[e], _parent[e]); 2271 } 2272 2273 _left.set(e, _left[arc]); 2274 _parent.set(_left[arc], e); 2275 _right.set(e, _right[arc]); 2276 _parent.set(_right[arc], e); 2277 2278 _parent.set(e, _parent[arc]); 2279 if (_parent[arc] != INVALID) { 2280 if (_left[_parent[arc]] == arc) { 2281 _left.set(_parent[arc], e); 2282 } else { 2283 _right.set(_parent[arc], e); 2284 } 2285 } 2286 splay(s); 2287 } else { 2288 _right.set(e, _right[arc]); 2289 _parent.set(_right[arc], e); 2290 2291 if (_parent[arc] != INVALID) { 2292 if (_left[_parent[arc]] == arc) { 2293 _left.set(_parent[arc], e); 2294 } else { 2295 _right.set(_parent[arc], e); 2296 } 2297 } else { 2298 _head.set(_g.source(arc), e); 2299 } 2300 } 2301 } 2302 } 2303 2304 Arc refreshRec(std::vector<Arc> &v,int a,int b) 2305 2305 { 2306 2306 int m=(a+b)/2; 2307 2307 Arc me=v[m]; 2308 2308 if (a < m) { 2309 2310 2311 2309 Arc left = refreshRec(v,a,m-1); 2310 _left.set(me, left); 2311 _parent.set(left, me); 2312 2312 } else { 2313 2313 _left.set(me, INVALID); 2314 2314 } 2315 2315 if (m < b) { 2316 2317 2318 2316 Arc right = refreshRec(v,m+1,b); 2317 _right.set(me, right); 2318 _parent.set(right, me); 2319 2319 } else { 2320 2320 _right.set(me, INVALID); 2321 2321 } 2322 2322 return me; … … 2325 2325 void refresh() { 2326 2326 for(NodeIt n(_g);n!=INVALID;++n) { 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 } 2337 } 2338 2339 void zig(Arc v) { 2327 std::vector<Arc> v; 2328 for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e); 2329 if(v.size()) { 2330 std::sort(v.begin(),v.end(),ArcLess(_g)); 2331 Arc head = refreshRec(v,0,v.size()-1); 2332 _head.set(n, head); 2333 _parent.set(head, INVALID); 2334 } 2335 else _head.set(n, INVALID); 2336 } 2337 } 2338 2339 void zig(Arc v) { 2340 2340 Arc w = _parent[v]; 2341 2341 _parent.set(v, _parent[w]); … … 2344 2344 _right.set(v, w); 2345 2345 if (_parent[v] != INVALID) { 2346 2347 2348 2349 2350 2346 if (_right[_parent[v]] == w) { 2347 _right.set(_parent[v], v); 2348 } else { 2349 _left.set(_parent[v], v); 2350 } 2351 2351 } 2352 2352 if (_left[w] != INVALID){ 2353 2354 } 2355 } 2356 2357 void zag(Arc v) { 2353 _parent.set(_left[w], w); 2354 } 2355 } 2356 2357 void zag(Arc v) { 2358 2358 Arc w = _parent[v]; 2359 2359 _parent.set(v, _parent[w]); … … 2362 2362 _left.set(v, w); 2363 2363 if (_parent[v] != INVALID){ 2364 2365 2366 2367 2368 2364 if (_left[_parent[v]] == w) { 2365 _left.set(_parent[v], v); 2366 } else { 2367 _right.set(_parent[v], v); 2368 } 2369 2369 } 2370 2370 if (_right[w] != INVALID){ 2371 2371 _parent.set(_right[w], w); 2372 2372 } 2373 2373 } … … 2375 2375 void splay(Arc v) { 2376 2376 while (_parent[v] != INVALID) { 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2377 if (v == _left[_parent[v]]) { 2378 if (_parent[_parent[v]] == INVALID) { 2379 zig(v); 2380 } else { 2381 if (_parent[v] == _left[_parent[_parent[v]]]) { 2382 zig(_parent[v]); 2383 zig(v); 2384 } else { 2385 zig(v); 2386 zag(v); 2387 } 2388 } 2389 } else { 2390 if (_parent[_parent[v]] == INVALID) { 2391 zag(v); 2392 } else { 2393 if (_parent[v] == _left[_parent[_parent[v]]]) { 2394 zag(v); 2395 zig(v); 2396 } else { 2397 zag(_parent[v]); 2398 zag(v); 2399 } 2400 } 2401 } 2402 2402 } 2403 2403 _head[_g.source(v)] = v; … … 2406 2406 2407 2407 public: 2408 2408 2409 2409 ///Find an arc between two nodes. 2410 2410 2411 2411 ///Find an arc between two nodes in time <em>O(</em>log<em>d)</em>, where 2412 2412 /// <em>d</em> is the number of outgoing arcs of \c s. … … 2419 2419 Arc a = _head[s]; 2420 2420 while (true) { 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2421 if (_g.target(a) == t) { 2422 const_cast<DynArcLookUp&>(*this).splay(a); 2423 return a; 2424 } else if (t < _g.target(a)) { 2425 if (_left[a] == INVALID) { 2426 const_cast<DynArcLookUp&>(*this).splay(a); 2427 return INVALID; 2428 } else { 2429 a = _left[a]; 2430 } 2431 } else { 2432 if (_right[a] == INVALID) { 2433 const_cast<DynArcLookUp&>(*this).splay(a); 2434 return INVALID; 2435 } else { 2436 a = _right[a]; 2437 } 2438 } 2439 2439 } 2440 2440 } 2441 2441 2442 2442 ///Find the first arc between two nodes. 2443 2443 2444 2444 ///Find the first arc between two nodes in time 2445 2445 /// <em>O(</em>log<em>d)</em>, where <em>d</em> is the number of 2446 /// outgoing arcs of \c s. 2447 ///\param s The source node 2446 /// outgoing arcs of \c s. 2447 ///\param s The source node 2448 2448 ///\param t The target node 2449 2449 ///\return An arc from \c s to \c t if there exists, \ref INVALID … … 2454 2454 Arc r = INVALID; 2455 2455 while (true) { 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2456 if (_g.target(a) < t) { 2457 if (_right[a] == INVALID) { 2458 const_cast<DynArcLookUp&>(*this).splay(a); 2459 return r; 2460 } else { 2461 a = _right[a]; 2462 } 2463 } else { 2464 if (_g.target(a) == t) { 2465 r = a; 2466 } 2467 if (_left[a] == INVALID) { 2468 const_cast<DynArcLookUp&>(*this).splay(a); 2469 return r; 2470 } else { 2471 a = _left[a]; 2472 } 2473 } 2474 2474 } 2475 2475 } 2476 2476 2477 2477 ///Find the next arc between two nodes. 2478 2478 2479 2479 ///Find the next arc between two nodes in time 2480 2480 /// <em>O(</em>log<em>d)</em>, where <em>d</em> is the number of 2481 /// outgoing arcs of \c s. 2482 ///\param s The source node 2481 /// outgoing arcs of \c s. 2482 ///\param s The source node 2483 2483 ///\param t The target node 2484 2484 ///\return An arc from \c s to \c t if there exists, \ref INVALID … … 2494 2494 { 2495 2495 if (_right[a] != INVALID) { 2496 2497 2498 2499 2500 2496 a = _right[a]; 2497 while (_left[a] != INVALID) { 2498 a = _left[a]; 2499 } 2500 const_cast<DynArcLookUp&>(*this).splay(a); 2501 2501 } else { 2502 2503 2504 2505 2506 2507 2508 2509 2510 2502 while (_parent[a] != INVALID && _right[_parent[a]] == a) { 2503 a = _parent[a]; 2504 } 2505 if (_parent[a] == INVALID) { 2506 return INVALID; 2507 } else { 2508 a = _parent[a]; 2509 const_cast<DynArcLookUp&>(*this).splay(a); 2510 } 2511 2511 } 2512 2512 if (_g.target(a) == t) return a; 2513 else return INVALID; 2513 else return INVALID; 2514 2514 } 2515 2515 … … 2517 2517 2518 2518 ///Fast arc look up between given endpoints. 2519 2519 2520 2520 ///\ingroup gutils 2521 2521 ///Using this class, you can find an arc in a digraph from a given … … 2534 2534 /// 2535 2535 ///\sa DynArcLookUp 2536 ///\sa AllArcLookUp 2536 ///\sa AllArcLookUp 2537 2537 template<class G> 2538 class ArcLookUp 2538 class ArcLookUp 2539 2539 { 2540 2540 public: … … 2547 2547 typename Digraph::template ArcMap<Arc> _left; 2548 2548 typename Digraph::template ArcMap<Arc> _right; 2549 2549 2550 2550 class ArcLess { 2551 2551 const Digraph &g; 2552 2552 public: 2553 2553 ArcLess(const Digraph &_g) : g(_g) {} 2554 bool operator()(Arc a,Arc b) const 2554 bool operator()(Arc a,Arc b) const 2555 2555 { 2556 2557 } 2558 }; 2559 2556 return g.target(a)<g.target(b); 2557 } 2558 }; 2559 2560 2560 public: 2561 2561 2562 2562 ///Constructor 2563 2563 … … 2567 2567 ///changes. 2568 2568 ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();} 2569 2569 2570 2570 private: 2571 Arc refreshRec(std::vector<Arc> &v,int a,int b) 2571 Arc refreshRec(std::vector<Arc> &v,int a,int b) 2572 2572 { 2573 2573 int m=(a+b)/2; … … 2584 2584 ///It runs in time <em>O(d</em>log<em>d)</em>, where <em>d</em> is 2585 2585 ///the number of the outgoing arcs of \c n. 2586 void refresh(Node n) 2586 void refresh(Node n) 2587 2587 { 2588 2588 std::vector<Arc> v; 2589 2589 for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e); 2590 2590 if(v.size()) { 2591 2592 2591 std::sort(v.begin(),v.end(),ArcLess(_g)); 2592 _head[n]=refreshRec(v,0,v.size()-1); 2593 2593 } 2594 2594 else _head[n]=INVALID; … … 2603 2603 ///out-degree of the digraph. 2604 2604 2605 void refresh() 2605 void refresh() 2606 2606 { 2607 2607 for(NodeIt n(_g);n!=INVALID;++n) refresh(n); 2608 2608 } 2609 2609 2610 2610 ///Find an arc between two nodes. 2611 2611 2612 2612 ///Find an arc between two nodes in time <em>O(</em>log<em>d)</em>, where 2613 2613 /// <em>d</em> is the number of outgoing arcs of \c s. … … 2626 2626 Arc e; 2627 2627 for(e=_head[s]; 2628 2629 2628 e!=INVALID&&_g.target(e)!=t; 2629 e = t < _g.target(e)?_left[e]:_right[e]) ; 2630 2630 return e; 2631 2631 } … … 2634 2634 2635 2635 ///Fast look up of all arcs between given endpoints. 2636 2636 2637 2637 ///\ingroup gutils 2638 2638 ///This class is the same as \ref ArcLookUp, with the addition … … 2647 2647 /// 2648 2648 ///\sa DynArcLookUp 2649 ///\sa ArcLookUp 2649 ///\sa ArcLookUp 2650 2650 template<class G> 2651 2651 class AllArcLookUp : public ArcLookUp<G> … … 2658 2658 TEMPLATE_DIGRAPH_TYPEDEFS(G); 2659 2659 typedef G Digraph; 2660 2660 2661 2661 typename Digraph::template ArcMap<Arc> _next; 2662 2662 2663 2663 Arc refreshNext(Arc head,Arc next=INVALID) 2664 2664 { 2665 2665 if(head==INVALID) return next; 2666 2666 else { 2667 2668 // 2669 2670 2671 2672 } 2673 } 2674 2667 next=refreshNext(_right[head],next); 2668 // _next[head]=next; 2669 _next[head]=( next!=INVALID && _g.target(next)==_g.target(head)) 2670 ? next : INVALID; 2671 return refreshNext(_left[head],head); 2672 } 2673 } 2674 2675 2675 void refreshNext() 2676 2676 { 2677 2677 for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]); 2678 2678 } 2679 2679 2680 2680 public: 2681 2681 ///Constructor … … 2693 2693 ///It runs in time <em>O(d</em>log<em>d)</em>, where <em>d</em> is 2694 2694 ///the number of the outgoing arcs of \c n. 2695 2696 void refresh(Node n) 2695 2696 void refresh(Node n) 2697 2697 { 2698 2698 ArcLookUp<G>::refresh(n); 2699 2699 refreshNext(_head[n]); 2700 2700 } 2701 2701 2702 2702 ///Refresh the full data structure. 2703 2703 … … 2709 2709 ///out-degree of the digraph. 2710 2710 2711 void refresh() 2711 void refresh() 2712 2712 { 2713 2713 for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]); 2714 2714 } 2715 2715 2716 2716 ///Find an arc between two nodes. 2717 2717 2718 2718 ///Find an arc between two nodes. 2719 2719 ///\param s The source node … … 2751 2751 } 2752 2752 #endif 2753 2753 2754 2754 }; 2755 2755 -
lemon/kruskal.h
r194 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 46 46 template <typename Digraph, typename In, typename Out> 47 47 typename disable_if<lemon::UndirectedTagIndicator<Digraph>, 48 48 typename In::value_type::second_type >::type 49 49 kruskal(const Digraph& digraph, const In& in, Out& out,dummy<0> = 0) { 50 50 typedef typename In::value_type::second_type Value; 51 51 typedef typename Digraph::template NodeMap<int> IndexMap; 52 52 typedef typename Digraph::Node Node; 53 53 54 54 IndexMap index(digraph); 55 55 UnionFind<IndexMap> uf(index); … … 57 57 uf.insert(it); 58 58 } 59 59 60 60 Value tree_value = 0; 61 61 for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) { … … 75 75 template <typename Graph, typename In, typename Out> 76 76 typename enable_if<lemon::UndirectedTagIndicator<Graph>, 77 77 typename In::value_type::second_type >::type 78 78 kruskal(const Graph& graph, const In& in, Out& out,dummy<1> = 1) { 79 79 typedef typename In::value_type::second_type Value; 80 80 typedef typename Graph::template NodeMap<int> IndexMap; 81 81 typedef typename Graph::Node Node; 82 82 83 83 IndexMap index(graph); 84 84 UnionFind<IndexMap> uf(index); … … 86 86 uf.insert(it); 87 87 } 88 88 89 89 Value tree_value = 0; 90 90 for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) { … … 105 105 typedef typename Sequence::value_type Value; 106 106 bool operator()(const Value& left, const Value& right) { 107 107 return left.second < right.second; 108 108 } 109 109 }; … … 115 115 116 116 template <typename In> 117 struct SequenceInputIndicator<In, 117 struct SequenceInputIndicator<In, 118 118 typename exists<typename In::value_type::first_type>::type> { 119 119 static const bool value = true; … … 126 126 127 127 template <typename In> 128 struct MapInputIndicator<In, 128 struct MapInputIndicator<In, 129 129 typename exists<typename In::Value>::type> { 130 130 static const bool value = true; … … 135 135 static const bool value = false; 136 136 }; 137 137 138 138 template <typename Out> 139 struct SequenceOutputIndicator<Out, 139 struct SequenceOutputIndicator<Out, 140 140 typename exists<typename Out::value_type>::type> { 141 141 static const bool value = true; … … 148 148 149 149 template <typename Out> 150 struct MapOutputIndicator<Out, 150 struct MapOutputIndicator<Out, 151 151 typename exists<typename Out::Value>::type> { 152 152 static const bool value = true; … … 158 158 template <typename In> 159 159 struct KruskalValueSelector<In, 160 typename enable_if<SequenceInputIndicator<In>, void>::type> 161 { 162 typedef typename In::value_type::second_type Value; 163 }; 160 typename enable_if<SequenceInputIndicator<In>, void>::type> 161 { 162 typedef typename In::value_type::second_type Value; 163 }; 164 164 165 165 template <typename In> 166 166 struct KruskalValueSelector<In, 167 typename enable_if<MapInputIndicator<In>, void>::type> 167 typename enable_if<MapInputIndicator<In>, void>::type> 168 168 { 169 169 typedef typename In::Value Value; 170 }; 171 170 }; 171 172 172 template <typename Graph, typename In, typename Out, 173 173 typename InEnable = void> … … 177 177 typename InEnable = void> 178 178 struct KruskalOutputSelector {}; 179 179 180 180 template <typename Graph, typename In, typename Out> 181 181 struct KruskalInputSelector<Graph, In, Out, 182 typename enable_if<SequenceInputIndicator<In>, void>::type > 182 typename enable_if<SequenceInputIndicator<In>, void>::type > 183 183 { 184 184 typedef typename In::value_type::second_type Value; … … 193 193 template <typename Graph, typename In, typename Out> 194 194 struct KruskalInputSelector<Graph, In, Out, 195 typename enable_if<MapInputIndicator<In>, void>::type > 195 typename enable_if<MapInputIndicator<In>, void>::type > 196 196 { 197 197 typedef typename In::Value Value; … … 202 202 typedef std::vector<std::pair<MapArc, Value> > Sequence; 203 203 Sequence seq; 204 204 205 205 for (MapArcIt it(graph); it != INVALID; ++it) { 206 206 seq.push_back(std::make_pair(it, in[it])); … … 225 225 template <typename Graph, typename In, typename Out> 226 226 struct KruskalOutputSelector<Graph, In, Out, 227 typename enable_if<SequenceOutputIndicator<Out>, void>::type > 227 typename enable_if<SequenceOutputIndicator<Out>, void>::type > 228 228 { 229 229 typedef typename In::value_type::second_type Value; … … 239 239 template <typename Graph, typename In, typename Out> 240 240 struct KruskalOutputSelector<Graph, In, Out, 241 typename enable_if<MapOutputIndicator<Out>, void>::type > 241 typename enable_if<MapOutputIndicator<Out>, void>::type > 242 242 { 243 243 typedef typename In::value_type::second_type Value; … … 255 255 /// a graph. 256 256 /// 257 /// This function runs Kruskal's algorithm to find a minimum cost 257 /// This function runs Kruskal's algorithm to find a minimum cost 258 258 /// spanning tree. 259 259 /// Due to some C++ hacking, it accepts various input and output types. 260 260 /// 261 261 /// \param g The graph the algorithm runs on. 262 /// It can be either \ref concepts::Digraph "directed" or 262 /// It can be either \ref concepts::Digraph "directed" or 263 263 /// \ref concepts::Graph "undirected". 264 /// If the graph is directed, the algorithm consider it to be 264 /// If the graph is directed, the algorithm consider it to be 265 265 /// undirected by disregarding the direction of the arcs. 266 266 /// 267 /// \param in This object is used to describe the arc/edge costs. 267 /// \param in This object is used to describe the arc/edge costs. 268 268 /// It can be one of the following choices. 269 269 /// - An STL compatible 'Forward Container' with … … 273 273 /// along with the assigned cost. <em>They must be in a 274 274 /// cost-ascending order.</em> 275 /// - Any readable arc/edge map. The values of the map indicate the 275 /// - Any readable arc/edge map. The values of the map indicate the 276 276 /// arc/edge costs. 277 277 /// … … 293 293 ///\endcode 294 294 /// Or if we don't know in advance the size of the tree, we can 295 /// write this. 295 /// write this. 296 296 ///\code 297 297 /// std::vector<Arc> tree; 298 /// kruskal(g,cost,std::back_inserter(tree)); 298 /// kruskal(g,cost,std::back_inserter(tree)); 299 299 ///\endcode 300 300 /// … … 308 308 template <class Graph, class In, class Out> 309 309 Value kruskal(GR const& g, const In& in, Out& out) 310 #else 310 #else 311 311 template <class Graph, class In, class Out> 312 inline typename _kruskal_bits::KruskalValueSelector<In>::Value 313 kruskal(const Graph& graph, const In& in, Out& out) 312 inline typename _kruskal_bits::KruskalValueSelector<In>::Value 313 kruskal(const Graph& graph, const In& in, Out& out) 314 314 #endif 315 315 { … … 318 318 } 319 319 320 321 320 321 322 322 323 323 template <class Graph, class In, class Out> … … 327 327 return _kruskal_bits::KruskalInputSelector<Graph, In, const Out>:: 328 328 kruskal(graph, in, out); 329 } 329 } 330 330 331 331 } //namespace lemon -
lemon/lgf_reader.h
r201 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 47 47 struct DefaultConverter { 48 48 Value operator()(const std::string& str) { 49 50 51 52 53 54 55 56 57 49 std::istringstream is(str); 50 Value value; 51 is >> value; 52 53 char c; 54 if (is >> std::ws >> c) { 55 throw DataFormatError("Remaining characters in token"); 56 } 57 return value; 58 58 } 59 59 }; … … 62 62 struct DefaultConverter<std::string> { 63 63 std::string operator()(const std::string& str) { 64 64 return str; 65 65 } 66 66 }; 67 67 68 template <typename _Item> 68 template <typename _Item> 69 69 class MapStorageBase { 70 70 public: … … 79 79 }; 80 80 81 template <typename _Item, typename _Map, 82 81 template <typename _Item, typename _Map, 82 typename _Converter = DefaultConverter<typename _Map::Value> > 83 83 class MapStorage : public MapStorageBase<_Item> { 84 84 public: … … 86 86 typedef _Converter Converter; 87 87 typedef _Item Item; 88 88 89 89 private: 90 90 Map& _map; … … 92 92 93 93 public: 94 MapStorage(Map& map, const Converter& converter = Converter()) 95 94 MapStorage(Map& map, const Converter& converter = Converter()) 95 : _map(map), _converter(converter) {} 96 96 virtual ~MapStorage() {} 97 97 98 98 virtual void set(const Item& item ,const std::string& value) { 99 99 _map.set(item, _converter(value)); 100 100 } 101 101 }; 102 102 103 template <typename _Graph, bool _dir, typename _Map, 104 103 template <typename _Graph, bool _dir, typename _Map, 104 typename _Converter = DefaultConverter<typename _Map::Value> > 105 105 class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> { 106 106 public: … … 110 110 typedef typename Graph::Edge Item; 111 111 static const bool dir = _dir; 112 112 113 113 private: 114 114 const Graph& _graph; … … 117 117 118 118 public: 119 GraphArcMapStorage(const Graph& graph, Map& map, 120 const Converter& converter = Converter()) 121 119 GraphArcMapStorage(const Graph& graph, Map& map, 120 const Converter& converter = Converter()) 121 : _graph(graph), _map(map), _converter(converter) {} 122 122 virtual ~GraphArcMapStorage() {} 123 123 124 124 virtual void set(const Item& item ,const std::string& value) { 125 125 _map.set(_graph.direct(item, dir), _converter(value)); 126 126 } 127 127 }; … … 147 147 public: 148 148 ValueStorage(Value& value, const Converter& converter = Converter()) 149 149 : _value(value), _converter(converter) {} 150 150 151 151 virtual void set(const std::string& value) { 152 152 _value = _converter(value); 153 153 } 154 154 }; … … 177 177 const Graph& _graph; 178 178 const std::map<std::string, typename Graph::Edge>& _map; 179 180 GraphArcLookUpConverter(const Graph& graph, 181 182 typename Graph::Edge>& map) 183 184 179 180 GraphArcLookUpConverter(const Graph& graph, 181 const std::map<std::string, 182 typename Graph::Edge>& map) 183 : _graph(graph), _map(map) {} 184 185 185 typename Graph::Arc operator()(const std::string& str) { 186 187 188 189 190 191 192 193 194 186 if (str.empty() || (str[0] != '+' && str[0] != '-')) { 187 throw DataFormatError("Item must start with '+' or '-'"); 188 } 189 typename std::map<std::string, typename Graph::Edge> 190 ::const_iterator it = _map.find(str.substr(1)); 191 if (it == _map.end()) { 192 throw DataFormatError("Item not found"); 193 } 194 return _graph.direct(it->second, str[0] == '+'); 195 195 } 196 196 }; 197 197 198 198 inline bool isWhiteSpace(char c) { 199 return c == ' ' || c == '\t' || c == '\v' || 200 c == '\n' || c == '\r' || c == '\f'; 201 } 202 199 return c == ' ' || c == '\t' || c == '\v' || 200 c == '\n' || c == '\r' || c == '\f'; 201 } 202 203 203 inline bool isOct(char c) { 204 return '0' <= c && c <='7'; 205 } 206 204 return '0' <= c && c <='7'; 205 } 206 207 207 inline int valueOct(char c) { 208 208 LEMON_ASSERT(isOct(c), "The character is not octal."); … … 211 211 212 212 inline bool isHex(char c) { 213 return ('0' <= c && c <= '9') || 214 ('a' <= c && c <= 'z') || 215 ('A' <= c && c <= 'Z'); 216 } 217 213 return ('0' <= c && c <= '9') || 214 ('a' <= c && c <= 'z') || 215 ('A' <= c && c <= 'Z'); 216 } 217 218 218 inline int valueHex(char c) { 219 219 LEMON_ASSERT(isHex(c), "The character is not hexadecimal."); … … 225 225 inline bool isIdentifierFirstChar(char c) { 226 226 return ('a' <= c && c <= 'z') || 227 227 ('A' <= c && c <= 'Z') || c == '_'; 228 228 } 229 229 230 230 inline bool isIdentifierChar(char c) { 231 231 return isIdentifierFirstChar(c) || 232 232 ('0' <= c && c <= '9'); 233 233 } 234 234 … … 236 236 char c; 237 237 if (!is.get(c)) 238 238 throw DataFormatError("Escape format error"); 239 239 240 240 switch (c) { 241 241 case '\\': 242 242 return '\\'; 243 243 case '\"': 244 244 return '\"'; 245 245 case '\'': 246 246 return '\''; 247 247 case '\?': 248 248 return '\?'; 249 249 case 'a': 250 250 return '\a'; 251 251 case 'b': 252 252 return '\b'; 253 253 case 'f': 254 254 return '\f'; 255 255 case 'n': 256 256 return '\n'; 257 257 case 'r': 258 258 return '\r'; 259 259 case 't': 260 260 return '\t'; 261 261 case 'v': 262 262 return '\v'; 263 263 case 'x': 264 265 266 if (!is.get(c) || !isHex(c)) 267 268 269 270 271 264 { 265 int code; 266 if (!is.get(c) || !isHex(c)) 267 throw DataFormatError("Escape format error"); 268 else if (code = valueHex(c), !is.get(c) || !isHex(c)) is.putback(c); 269 else code = code * 16 + valueHex(c); 270 return code; 271 } 272 272 default: 273 274 275 if (!isOct(c)) 276 277 else if (code = valueOct(c), !is.get(c) || !isOct(c)) 278 279 else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c)) 280 281 282 283 } 284 } 285 } 286 273 { 274 int code; 275 if (!isOct(c)) 276 throw DataFormatError("Escape format error"); 277 else if (code = valueOct(c), !is.get(c) || !isOct(c)) 278 is.putback(c); 279 else if (code = code * 8 + valueOct(c), !is.get(c) || !isOct(c)) 280 is.putback(c); 281 else code = code * 8 + valueOct(c); 282 return code; 283 } 284 } 285 } 286 287 287 inline std::istream& readToken(std::istream& is, std::string& str) { 288 288 std::ostringstream os; … … 290 290 char c; 291 291 is >> std::ws; 292 293 if (!is.get(c)) 294 292 293 if (!is.get(c)) 294 return is; 295 295 296 296 if (c == '\"') { 297 298 if (c == '\\') 299 300 301 302 if (!is) 303 297 while (is.get(c) && c != '\"') { 298 if (c == '\\') 299 c = readEscape(is); 300 os << c; 301 } 302 if (!is) 303 throw DataFormatError("Quoted format error"); 304 304 } else { 305 306 307 if (c == '\\') 308 309 310 311 312 313 314 315 305 is.putback(c); 306 while (is.get(c) && !isWhiteSpace(c)) { 307 if (c == '\\') 308 c = readEscape(is); 309 os << c; 310 } 311 if (!is) { 312 is.clear(); 313 } else { 314 is.putback(c); 315 } 316 316 } 317 317 str = os.str(); … … 332 332 333 333 public: 334 334 335 335 LineSection(const Functor& functor) : _functor(functor) {} 336 336 virtual ~LineSection() {} 337 337 338 338 virtual void process(std::istream& is, int& line_num) { 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 339 char c; 340 std::string line; 341 while (is.get(c) && c != '@') { 342 if (c == '\n') { 343 ++line_num; 344 } else if (c == '#') { 345 getline(is, line); 346 ++line_num; 347 } else if (!isWhiteSpace(c)) { 348 is.putback(c); 349 getline(is, line); 350 _functor(line); 351 ++line_num; 352 } 353 } 354 if (is) is.putback(c); 355 else if (is.eof()) is.clear(); 356 356 } 357 357 }; … … 364 364 365 365 public: 366 366 367 367 StreamSection(const Functor& functor) : _functor(functor) {} 368 virtual ~StreamSection() {} 368 virtual ~StreamSection() {} 369 369 370 370 virtual void process(std::istream& is, int& line_num) { 371 372 373 374 375 376 377 378 379 380 381 382 383 else if (is.eof()) is.clear(); 371 _functor(is, line_num); 372 char c; 373 std::string line; 374 while (is.get(c) && c != '@') { 375 if (c == '\n') { 376 ++line_num; 377 } else if (!isWhiteSpace(c)) { 378 getline(is, line); 379 ++line_num; 380 } 381 } 382 if (is) is.putback(c); 383 else if (is.eof()) is.clear(); 384 384 } 385 385 }; 386 386 387 387 } 388 388 … … 400 400 401 401 /// \ingroup lemon_io 402 /// 402 /// 403 403 /// \brief \ref lgf-format "LGF" reader for directed graphs 404 404 /// … … 454 454 typedef _Digraph Digraph; 455 455 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph); 456 456 457 457 private: 458 458 … … 471 471 typedef std::map<std::string, Arc> ArcIndex; 472 472 ArcIndex _arc_index; 473 474 typedef std::vector<std::pair<std::string, 475 _reader_bits::MapStorageBase<Node>*> > NodeMaps; 476 NodeMaps _node_maps; 473 474 typedef std::vector<std::pair<std::string, 475 _reader_bits::MapStorageBase<Node>*> > NodeMaps; 476 NodeMaps _node_maps; 477 477 478 478 typedef std::vector<std::pair<std::string, … … 480 480 ArcMaps _arc_maps; 481 481 482 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*> 482 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*> 483 483 Attributes; 484 484 Attributes _attributes; … … 499 499 /// Construct a directed graph reader, which reads from the given 500 500 /// input stream. 501 DigraphReader(std::istream& is, Digraph& digraph) 501 DigraphReader(std::istream& is, Digraph& digraph) 502 502 : _is(&is), local_is(false), _digraph(digraph), 503 504 503 _use_nodes(false), _use_arcs(false), 504 _skip_nodes(false), _skip_arcs(false) {} 505 505 506 506 /// \brief Constructor … … 508 508 /// Construct a directed graph reader, which reads from the given 509 509 /// file. 510 DigraphReader(const std::string& fn, Digraph& digraph) 510 DigraphReader(const std::string& fn, Digraph& digraph) 511 511 : _is(new std::ifstream(fn.c_str())), local_is(true), _digraph(digraph), 512 513 514 512 _use_nodes(false), _use_arcs(false), 513 _skip_nodes(false), _skip_arcs(false) {} 514 515 515 /// \brief Constructor 516 516 /// 517 517 /// Construct a directed graph reader, which reads from the given 518 518 /// file. 519 DigraphReader(const char* fn, Digraph& digraph) 519 DigraphReader(const char* fn, Digraph& digraph) 520 520 : _is(new std::ifstream(fn)), local_is(true), _digraph(digraph), 521 522 521 _use_nodes(false), _use_arcs(false), 522 _skip_nodes(false), _skip_arcs(false) {} 523 523 524 524 /// \brief Destructor 525 525 ~DigraphReader() { 526 for (typename NodeMaps::iterator it = _node_maps.begin(); 527 528 529 } 530 531 for (typename ArcMaps::iterator it = _arc_maps.begin(); 532 533 534 } 535 536 for (typename Attributes::iterator it = _attributes.begin(); 537 538 526 for (typename NodeMaps::iterator it = _node_maps.begin(); 527 it != _node_maps.end(); ++it) { 528 delete it->second; 529 } 530 531 for (typename ArcMaps::iterator it = _arc_maps.begin(); 532 it != _arc_maps.end(); ++it) { 533 delete it->second; 534 } 535 536 for (typename Attributes::iterator it = _attributes.begin(); 537 it != _attributes.end(); ++it) { 538 delete it->second; 539 539 } 540 540 541 541 if (local_is) { 542 542 delete _is; 543 543 } 544 544 … … 547 547 private: 548 548 549 friend DigraphReader<Digraph> digraphReader<>(std::istream& is, 550 Digraph& digraph); 551 friend DigraphReader<Digraph> digraphReader<>(const std::string& fn, 552 Digraph& digraph); 553 friend DigraphReader<Digraph> digraphReader<>(const char *fn, 554 Digraph& digraph); 555 556 DigraphReader(DigraphReader& other) 549 friend DigraphReader<Digraph> digraphReader<>(std::istream& is, 550 Digraph& digraph); 551 friend DigraphReader<Digraph> digraphReader<>(const std::string& fn, 552 Digraph& digraph); 553 friend DigraphReader<Digraph> digraphReader<>(const char *fn, 554 Digraph& digraph); 555 556 DigraphReader(DigraphReader& other) 557 557 : _is(other._is), local_is(other.local_is), _digraph(other._digraph), 558 559 558 _use_nodes(other._use_nodes), _use_arcs(other._use_arcs), 559 _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) { 560 560 561 561 other._is = 0; 562 562 other.local_is = false; 563 563 564 564 _node_index.swap(other._node_index); 565 565 _arc_index.swap(other._arc_index); … … 581 581 /// \name Reading rules 582 582 /// @{ 583 583 584 584 /// \brief Node map reading rule 585 585 /// … … 588 588 DigraphReader& nodeMap(const std::string& caption, Map& map) { 589 589 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>(); 590 _reader_bits::MapStorageBase<Node>* storage = 591 590 _reader_bits::MapStorageBase<Node>* storage = 591 new _reader_bits::MapStorage<Node, Map>(map); 592 592 _node_maps.push_back(std::make_pair(caption, storage)); 593 593 return *this; … … 599 599 /// reader. 600 600 template <typename Map, typename Converter> 601 DigraphReader& nodeMap(const std::string& caption, Map& map, 602 601 DigraphReader& nodeMap(const std::string& caption, Map& map, 602 const Converter& converter = Converter()) { 603 603 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>(); 604 _reader_bits::MapStorageBase<Node>* storage = 605 604 _reader_bits::MapStorageBase<Node>* storage = 605 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter); 606 606 _node_maps.push_back(std::make_pair(caption, storage)); 607 607 return *this; … … 614 614 DigraphReader& arcMap(const std::string& caption, Map& map) { 615 615 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>(); 616 _reader_bits::MapStorageBase<Arc>* storage = 617 616 _reader_bits::MapStorageBase<Arc>* storage = 617 new _reader_bits::MapStorage<Arc, Map>(map); 618 618 _arc_maps.push_back(std::make_pair(caption, storage)); 619 619 return *this; … … 625 625 /// reader. 626 626 template <typename Map, typename Converter> 627 DigraphReader& arcMap(const std::string& caption, Map& map, 628 627 DigraphReader& arcMap(const std::string& caption, Map& map, 628 const Converter& converter = Converter()) { 629 629 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>(); 630 _reader_bits::MapStorageBase<Arc>* storage = 631 630 _reader_bits::MapStorageBase<Arc>* storage = 631 new _reader_bits::MapStorage<Arc, Map, Converter>(map, converter); 632 632 _arc_maps.push_back(std::make_pair(caption, storage)); 633 633 return *this; … … 639 639 template <typename Value> 640 640 DigraphReader& attribute(const std::string& caption, Value& value) { 641 _reader_bits::ValueStorageBase* storage = 642 641 _reader_bits::ValueStorageBase* storage = 642 new _reader_bits::ValueStorage<Value>(value); 643 643 _attributes.insert(std::make_pair(caption, storage)); 644 644 return *this; … … 650 650 /// reader. 651 651 template <typename Value, typename Converter> 652 DigraphReader& attribute(const std::string& caption, Value& value, 653 654 _reader_bits::ValueStorageBase* storage = 655 652 DigraphReader& attribute(const std::string& caption, Value& value, 653 const Converter& converter = Converter()) { 654 _reader_bits::ValueStorageBase* storage = 655 new _reader_bits::ValueStorage<Value, Converter>(value, converter); 656 656 _attributes.insert(std::make_pair(caption, storage)); 657 657 return *this; … … 664 664 typedef _reader_bits::MapLookUpConverter<Node> Converter; 665 665 Converter converter(_node_index); 666 _reader_bits::ValueStorageBase* storage = 667 666 _reader_bits::ValueStorageBase* storage = 667 new _reader_bits::ValueStorage<Node, Converter>(node, converter); 668 668 _attributes.insert(std::make_pair(caption, storage)); 669 669 return *this; … … 676 676 typedef _reader_bits::MapLookUpConverter<Arc> Converter; 677 677 Converter converter(_arc_index); 678 _reader_bits::ValueStorageBase* storage = 679 678 _reader_bits::ValueStorageBase* storage = 679 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter); 680 680 _attributes.insert(std::make_pair(caption, storage)); 681 681 return *this; … … 723 723 DigraphReader& useNodes(const Map& map) { 724 724 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 725 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 725 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 726 726 _use_nodes = true; 727 727 _writer_bits::DefaultConverter<typename Map::Value> converter; 728 728 for (NodeIt n(_digraph); n != INVALID; ++n) { 729 729 _node_index.insert(std::make_pair(converter(map[n]), n)); 730 730 } 731 731 return *this; … … 738 738 /// \c std::string. 739 739 template <typename Map, typename Converter> 740 DigraphReader& useNodes(const Map& map, 741 740 DigraphReader& useNodes(const Map& map, 741 const Converter& converter = Converter()) { 742 742 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 743 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 743 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 744 744 _use_nodes = true; 745 745 for (NodeIt n(_digraph); n != INVALID; ++n) { 746 746 _node_index.insert(std::make_pair(converter(map[n]), n)); 747 747 } 748 748 return *this; … … 760 760 _writer_bits::DefaultConverter<typename Map::Value> converter; 761 761 for (ArcIt a(_digraph); a != INVALID; ++a) { 762 762 _arc_index.insert(std::make_pair(converter(map[a]), a)); 763 763 } 764 764 return *this; … … 771 771 /// \c std::string. 772 772 template <typename Map, typename Converter> 773 DigraphReader& useArcs(const Map& map, 774 773 DigraphReader& useArcs(const Map& map, 774 const Converter& converter = Converter()) { 775 775 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>(); 776 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member"); 776 LEMON_ASSERT(!_use_arcs, "Multiple usage of useArcs() member"); 777 777 _use_arcs = true; 778 778 for (ArcIt a(_digraph); a != INVALID; ++a) { 779 779 _arc_index.insert(std::make_pair(converter(map[a]), a)); 780 780 } 781 781 return *this; … … 791 791 /// \c useNodes() should be used to specify the label of the nodes. 792 792 DigraphReader& skipNodes() { 793 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set"); 793 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set"); 794 794 _skip_nodes = true; 795 795 return *this; … … 802 802 /// will not be constructed. 803 803 DigraphReader& skipArcs() { 804 LEMON_ASSERT(!_skip_arcs, "Skip arcs already set"); 804 LEMON_ASSERT(!_skip_arcs, "Skip arcs already set"); 805 805 _skip_arcs = true; 806 806 return *this; … … 814 814 std::string str; 815 815 while(++line_num, std::getline(*_is, str)) { 816 817 818 819 820 821 816 line.clear(); line.str(str); 817 char c; 818 if (line >> std::ws >> c && c != '#') { 819 line.putback(c); 820 return true; 821 } 822 822 } 823 823 return false; … … 827 827 return static_cast<bool>(*_is); 828 828 } 829 829 830 830 void skipSection() { 831 831 char c; 832 832 while (readSuccess() && line >> c && c != '@') { 833 833 readLine(); 834 834 } 835 835 line.putback(c); … … 843 843 char c; 844 844 if (!readLine() || !(line >> c) || c == '@') { 845 846 if (!_node_maps.empty()) 847 848 845 if (readSuccess() && line) line.putback(c); 846 if (!_node_maps.empty()) 847 throw DataFormatError("Cannot find map names"); 848 return; 849 849 } 850 850 line.putback(c); 851 851 852 852 { 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 std::map<std::string, int>::iterator jt = 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 853 std::map<std::string, int> maps; 854 855 std::string map; 856 int index = 0; 857 while (_reader_bits::readToken(line, map)) { 858 if (maps.find(map) != maps.end()) { 859 std::ostringstream msg; 860 msg << "Multiple occurence of node map: " << map; 861 throw DataFormatError(msg.str().c_str()); 862 } 863 maps.insert(std::make_pair(map, index)); 864 ++index; 865 } 866 867 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) { 868 std::map<std::string, int>::iterator jt = 869 maps.find(_node_maps[i].first); 870 if (jt == maps.end()) { 871 std::ostringstream msg; 872 msg << "Map not found in file: " << _node_maps[i].first; 873 throw DataFormatError(msg.str().c_str()); 874 } 875 map_index[i] = jt->second; 876 } 877 878 { 879 std::map<std::string, int>::iterator jt = maps.find("label"); 880 if (jt != maps.end()) { 881 label_index = jt->second; 882 } else { 883 label_index = -1; 884 } 885 } 886 map_num = maps.size(); 887 887 } 888 888 889 889 while (readLine() && line >> c && c != '@') { 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 if (label_index == -1) 910 911 912 913 914 915 916 throw DataFormatError(msg.str().c_str()); 917 918 919 920 921 922 923 890 line.putback(c); 891 892 std::vector<std::string> tokens(map_num); 893 for (int i = 0; i < map_num; ++i) { 894 if (!_reader_bits::readToken(line, tokens[i])) { 895 std::ostringstream msg; 896 msg << "Column not found (" << i + 1 << ")"; 897 throw DataFormatError(msg.str().c_str()); 898 } 899 } 900 if (line >> std::ws >> c) 901 throw DataFormatError("Extra character on the end of line"); 902 903 Node n; 904 if (!_use_nodes) { 905 n = _digraph.addNode(); 906 if (label_index != -1) 907 _node_index.insert(std::make_pair(tokens[label_index], n)); 908 } else { 909 if (label_index == -1) 910 throw DataFormatError("Label map not found in file"); 911 typename std::map<std::string, Node>::iterator it = 912 _node_index.find(tokens[label_index]); 913 if (it == _node_index.end()) { 914 std::ostringstream msg; 915 msg << "Node with label not found: " << tokens[label_index]; 916 throw DataFormatError(msg.str().c_str()); 917 } 918 n = it->second; 919 } 920 921 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) { 922 _node_maps[i].second->set(n, tokens[map_index[i]]); 923 } 924 924 925 925 } 926 926 if (readSuccess()) { 927 927 line.putback(c); 928 928 } 929 929 } … … 936 936 char c; 937 937 if (!readLine() || !(line >> c) || c == '@') { 938 939 if (!_arc_maps.empty()) 940 941 938 if (readSuccess() && line) line.putback(c); 939 if (!_arc_maps.empty()) 940 throw DataFormatError("Cannot find map names"); 941 return; 942 942 } 943 943 line.putback(c); 944 944 945 945 { 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 std::map<std::string, int>::iterator jt = 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 946 std::map<std::string, int> maps; 947 948 std::string map; 949 int index = 0; 950 while (_reader_bits::readToken(line, map)) { 951 if (maps.find(map) != maps.end()) { 952 std::ostringstream msg; 953 msg << "Multiple occurence of arc map: " << map; 954 throw DataFormatError(msg.str().c_str()); 955 } 956 maps.insert(std::make_pair(map, index)); 957 ++index; 958 } 959 960 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) { 961 std::map<std::string, int>::iterator jt = 962 maps.find(_arc_maps[i].first); 963 if (jt == maps.end()) { 964 std::ostringstream msg; 965 msg << "Map not found in file: " << _arc_maps[i].first; 966 throw DataFormatError(msg.str().c_str()); 967 } 968 map_index[i] = jt->second; 969 } 970 971 { 972 std::map<std::string, int>::iterator jt = maps.find("label"); 973 if (jt != maps.end()) { 974 label_index = jt->second; 975 } else { 976 label_index = -1; 977 } 978 } 979 map_num = maps.size(); 980 980 } 981 981 982 982 while (readLine() && line >> c && c != '@') { 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 983 line.putback(c); 984 985 std::string source_token; 986 std::string target_token; 987 988 if (!_reader_bits::readToken(line, source_token)) 989 throw DataFormatError("Source not found"); 990 991 if (!_reader_bits::readToken(line, target_token)) 992 throw DataFormatError("Target not found"); 993 994 std::vector<std::string> tokens(map_num); 995 for (int i = 0; i < map_num; ++i) { 996 if (!_reader_bits::readToken(line, tokens[i])) { 997 std::ostringstream msg; 998 msg << "Column not found (" << i + 1 << ")"; 999 throw DataFormatError(msg.str().c_str()); 1000 } 1001 } 1002 if (line >> std::ws >> c) 1003 throw DataFormatError("Extra character on the end of line"); 1004 1005 Arc a; 1006 if (!_use_arcs) { 1007 1007 1008 1008 typename NodeIndex::iterator it; 1009 1009 1010 1010 it = _node_index.find(source_token); 1011 1011 if (it == _node_index.end()) { … … 1017 1017 1018 1018 it = _node_index.find(target_token); 1019 if (it == _node_index.end()) { 1020 std::ostringstream msg; 1019 if (it == _node_index.end()) { 1020 std::ostringstream msg; 1021 1021 msg << "Item not found: " << target_token; 1022 1022 throw DataFormatError(msg.str().c_str()); 1023 } 1024 Node target = it->second; 1025 1026 1027 if (label_index != -1) 1028 1029 1030 if (label_index == -1) 1031 1032 1033 1034 1035 1036 1037 throw DataFormatError(msg.str().c_str()); 1038 1039 1040 1041 1042 1043 1044 1023 } 1024 Node target = it->second; 1025 1026 a = _digraph.addArc(source, target); 1027 if (label_index != -1) 1028 _arc_index.insert(std::make_pair(tokens[label_index], a)); 1029 } else { 1030 if (label_index == -1) 1031 throw DataFormatError("Label map not found in file"); 1032 typename std::map<std::string, Arc>::iterator it = 1033 _arc_index.find(tokens[label_index]); 1034 if (it == _arc_index.end()) { 1035 std::ostringstream msg; 1036 msg << "Arc with label not found: " << tokens[label_index]; 1037 throw DataFormatError(msg.str().c_str()); 1038 } 1039 a = it->second; 1040 } 1041 1042 for (int i = 0; i < static_cast<int>(_arc_maps.size()); ++i) { 1043 _arc_maps[i].second->set(a, tokens[map_index[i]]); 1044 } 1045 1045 1046 1046 } 1047 1047 if (readSuccess()) { 1048 1048 line.putback(c); 1049 1049 } 1050 1050 } … … 1056 1056 char c; 1057 1057 while (readLine() && line >> c && c != '@') { 1058 1059 1060 1061 1062 1063 1064 1065 1066 throw DataFormatError("Extra character on the end of line"); 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1058 line.putback(c); 1059 1060 std::string attr, token; 1061 if (!_reader_bits::readToken(line, attr)) 1062 throw DataFormatError("Attribute name not found"); 1063 if (!_reader_bits::readToken(line, token)) 1064 throw DataFormatError("Attribute value not found"); 1065 if (line >> c) 1066 throw DataFormatError("Extra character on the end of line"); 1067 1068 { 1069 std::set<std::string>::iterator it = read_attr.find(attr); 1070 if (it != read_attr.end()) { 1071 std::ostringstream msg; 1072 msg << "Multiple occurence of attribute " << attr; 1073 throw DataFormatError(msg.str().c_str()); 1074 } 1075 read_attr.insert(attr); 1076 } 1077 1078 { 1079 typename Attributes::iterator it = _attributes.lower_bound(attr); 1080 while (it != _attributes.end() && it->first == attr) { 1081 it->second->set(token); 1082 ++it; 1083 } 1084 } 1085 1085 1086 1086 } 1087 1087 if (readSuccess()) { 1088 1088 line.putback(c); 1089 1089 } 1090 1090 for (typename Attributes::iterator it = _attributes.begin(); 1091 1092 1093 1094 1095 1096 } 1091 it != _attributes.end(); ++it) { 1092 if (read_attr.find(it->first) == read_attr.end()) { 1093 std::ostringstream msg; 1094 msg << "Attribute not found in file: " << it->first; 1095 throw DataFormatError(msg.str().c_str()); 1096 } 1097 1097 } 1098 1098 } … … 1100 1100 public: 1101 1101 1102 /// \name Execution of the reader 1102 /// \name Execution of the reader 1103 1103 /// @{ 1104 1104 … … 1109 1109 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader"); 1110 1110 if (!*_is) { 1111 1112 } 1113 1111 throw DataFormatError("Cannot find file"); 1112 } 1113 1114 1114 bool nodes_done = _skip_nodes; 1115 1115 bool arcs_done = _skip_arcs; 1116 1116 bool attributes_done = false; 1117 1117 1118 line_num = 0; 1118 line_num = 0; 1119 1119 readLine(); 1120 1120 skipSection(); 1121 1121 1122 1122 while (readSuccess()) { 1123 1124 1125 1126 1127 1128 1129 1130 if (line >> c) 1131 1132 1133 1134 1135 1136 1137 1138 } else if ((section == "arcs" || section == "edges") && 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 } 1123 try { 1124 char c; 1125 std::string section, caption; 1126 line >> c; 1127 _reader_bits::readToken(line, section); 1128 _reader_bits::readToken(line, caption); 1129 1130 if (line >> c) 1131 throw DataFormatError("Extra character on the end of line"); 1132 1133 if (section == "nodes" && !nodes_done) { 1134 if (_nodes_caption.empty() || _nodes_caption == caption) { 1135 readNodes(); 1136 nodes_done = true; 1137 } 1138 } else if ((section == "arcs" || section == "edges") && 1139 !arcs_done) { 1140 if (_arcs_caption.empty() || _arcs_caption == caption) { 1141 readArcs(); 1142 arcs_done = true; 1143 } 1144 } else if (section == "attributes" && !attributes_done) { 1145 if (_attributes_caption.empty() || _attributes_caption == caption) { 1146 readAttributes(); 1147 attributes_done = true; 1148 } 1149 } else { 1150 readLine(); 1151 skipSection(); 1152 } 1153 } catch (DataFormatError& error) { 1154 error.line(line_num); 1155 throw; 1156 } 1157 1157 } 1158 1158 1159 1159 if (!nodes_done) { 1160 1160 throw DataFormatError("Section @nodes not found"); 1161 1161 } 1162 1162 1163 1163 if (!arcs_done) { 1164 1164 throw DataFormatError("Section @arcs not found"); 1165 1165 } 1166 1166 1167 1167 if (!attributes_done && !_attributes.empty()) { 1168 1168 throw DataFormatError("Section @attributes not found"); 1169 1169 } 1170 1170 … … 1172 1172 1173 1173 /// @} 1174 1174 1175 1175 }; 1176 1176 1177 1177 /// \brief Return a \ref DigraphReader class 1178 /// 1178 /// 1179 1179 /// This function just returns a \ref DigraphReader class. 1180 1180 /// \relates DigraphReader … … 1186 1186 1187 1187 /// \brief Return a \ref DigraphReader class 1188 /// 1188 /// 1189 1189 /// This function just returns a \ref DigraphReader class. 1190 1190 /// \relates DigraphReader 1191 1191 template <typename Digraph> 1192 DigraphReader<Digraph> digraphReader(const std::string& fn, 1193 1192 DigraphReader<Digraph> digraphReader(const std::string& fn, 1193 Digraph& digraph) { 1194 1194 DigraphReader<Digraph> tmp(fn, digraph); 1195 1195 return tmp; … … 1197 1197 1198 1198 /// \brief Return a \ref DigraphReader class 1199 /// 1199 /// 1200 1200 /// This function just returns a \ref DigraphReader class. 1201 1201 /// \relates DigraphReader … … 1210 1210 1211 1211 template <typename Graph> 1212 GraphReader<Graph> graphReader(std::istream& is, Graph& graph); 1212 GraphReader<Graph> graphReader(std::istream& is, Graph& graph); 1213 1213 1214 1214 template <typename Graph> 1215 GraphReader<Graph> graphReader(const std::string& fn, Graph& graph); 1215 GraphReader<Graph> graphReader(const std::string& fn, Graph& graph); 1216 1216 1217 1217 template <typename Graph> 1218 GraphReader<Graph> graphReader(const char *fn, Graph& graph); 1218 GraphReader<Graph> graphReader(const char *fn, Graph& graph); 1219 1219 1220 1220 /// \ingroup lemon_io 1221 /// 1221 /// 1222 1222 /// \brief \ref lgf-format "LGF" reader for undirected graphs 1223 1223 /// … … 1239 1239 typedef _Graph Graph; 1240 1240 TEMPLATE_GRAPH_TYPEDEFS(Graph); 1241 1241 1242 1242 private: 1243 1243 … … 1255 1255 typedef std::map<std::string, Edge> EdgeIndex; 1256 1256 EdgeIndex _edge_index; 1257 1258 typedef std::vector<std::pair<std::string, 1259 _reader_bits::MapStorageBase<Node>*> > NodeMaps; 1260 NodeMaps _node_maps; 1257 1258 typedef std::vector<std::pair<std::string, 1259 _reader_bits::MapStorageBase<Node>*> > NodeMaps; 1260 NodeMaps _node_maps; 1261 1261 1262 1262 typedef std::vector<std::pair<std::string, … … 1264 1264 EdgeMaps _edge_maps; 1265 1265 1266 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*> 1266 typedef std::multimap<std::string, _reader_bits::ValueStorageBase*> 1267 1267 Attributes; 1268 1268 Attributes _attributes; … … 1283 1283 /// Construct an undirected graph reader, which reads from the given 1284 1284 /// input stream. 1285 GraphReader(std::istream& is, Graph& graph) 1285 GraphReader(std::istream& is, Graph& graph) 1286 1286 : _is(&is), local_is(false), _graph(graph), 1287 1288 1287 _use_nodes(false), _use_edges(false), 1288 _skip_nodes(false), _skip_edges(false) {} 1289 1289 1290 1290 /// \brief Constructor … … 1292 1292 /// Construct an undirected graph reader, which reads from the given 1293 1293 /// file. 1294 GraphReader(const std::string& fn, Graph& graph) 1294 GraphReader(const std::string& fn, Graph& graph) 1295 1295 : _is(new std::ifstream(fn.c_str())), local_is(true), _graph(graph), 1296 1297 1298 1296 _use_nodes(false), _use_edges(false), 1297 _skip_nodes(false), _skip_edges(false) {} 1298 1299 1299 /// \brief Constructor 1300 1300 /// 1301 1301 /// Construct an undirected graph reader, which reads from the given 1302 1302 /// file. 1303 GraphReader(const char* fn, Graph& graph) 1303 GraphReader(const char* fn, Graph& graph) 1304 1304 : _is(new std::ifstream(fn)), local_is(true), _graph(graph), 1305 1306 1305 _use_nodes(false), _use_edges(false), 1306 _skip_nodes(false), _skip_edges(false) {} 1307 1307 1308 1308 /// \brief Destructor 1309 1309 ~GraphReader() { 1310 for (typename NodeMaps::iterator it = _node_maps.begin(); 1311 1312 1313 } 1314 1315 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 1316 1317 1318 } 1319 1320 for (typename Attributes::iterator it = _attributes.begin(); 1321 1322 1310 for (typename NodeMaps::iterator it = _node_maps.begin(); 1311 it != _node_maps.end(); ++it) { 1312 delete it->second; 1313 } 1314 1315 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 1316 it != _edge_maps.end(); ++it) { 1317 delete it->second; 1318 } 1319 1320 for (typename Attributes::iterator it = _attributes.begin(); 1321 it != _attributes.end(); ++it) { 1322 delete it->second; 1323 1323 } 1324 1324 1325 1325 if (local_is) { 1326 1326 delete _is; 1327 1327 } 1328 1328 … … 1330 1330 1331 1331 private: 1332 friend GraphReader<Graph> graphReader<>(std::istream& is, Graph& graph); 1333 friend GraphReader<Graph> graphReader<>(const std::string& fn, 1334 Graph& graph); 1335 friend GraphReader<Graph> graphReader<>(const char *fn, Graph& graph); 1336 1337 GraphReader(GraphReader& other) 1332 friend GraphReader<Graph> graphReader<>(std::istream& is, Graph& graph); 1333 friend GraphReader<Graph> graphReader<>(const std::string& fn, 1334 Graph& graph); 1335 friend GraphReader<Graph> graphReader<>(const char *fn, Graph& graph); 1336 1337 GraphReader(GraphReader& other) 1338 1338 : _is(other._is), local_is(other.local_is), _graph(other._graph), 1339 1340 1339 _use_nodes(other._use_nodes), _use_edges(other._use_edges), 1340 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) { 1341 1341 1342 1342 other._is = 0; 1343 1343 other.local_is = false; 1344 1344 1345 1345 _node_index.swap(other._node_index); 1346 1346 _edge_index.swap(other._edge_index); … … 1362 1362 /// \name Reading rules 1363 1363 /// @{ 1364 1364 1365 1365 /// \brief Node map reading rule 1366 1366 /// … … 1369 1369 GraphReader& nodeMap(const std::string& caption, Map& map) { 1370 1370 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>(); 1371 _reader_bits::MapStorageBase<Node>* storage = 1372 1371 _reader_bits::MapStorageBase<Node>* storage = 1372 new _reader_bits::MapStorage<Node, Map>(map); 1373 1373 _node_maps.push_back(std::make_pair(caption, storage)); 1374 1374 return *this; … … 1380 1380 /// reader. 1381 1381 template <typename Map, typename Converter> 1382 GraphReader& nodeMap(const std::string& caption, Map& map, 1383 1382 GraphReader& nodeMap(const std::string& caption, Map& map, 1383 const Converter& converter = Converter()) { 1384 1384 checkConcept<concepts::WriteMap<Node, typename Map::Value>, Map>(); 1385 _reader_bits::MapStorageBase<Node>* storage = 1386 1385 _reader_bits::MapStorageBase<Node>* storage = 1386 new _reader_bits::MapStorage<Node, Map, Converter>(map, converter); 1387 1387 _node_maps.push_back(std::make_pair(caption, storage)); 1388 1388 return *this; … … 1395 1395 GraphReader& edgeMap(const std::string& caption, Map& map) { 1396 1396 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>(); 1397 _reader_bits::MapStorageBase<Edge>* storage = 1398 1397 _reader_bits::MapStorageBase<Edge>* storage = 1398 new _reader_bits::MapStorage<Edge, Map>(map); 1399 1399 _edge_maps.push_back(std::make_pair(caption, storage)); 1400 1400 return *this; … … 1406 1406 /// reader. 1407 1407 template <typename Map, typename Converter> 1408 GraphReader& edgeMap(const std::string& caption, Map& map, 1409 1408 GraphReader& edgeMap(const std::string& caption, Map& map, 1409 const Converter& converter = Converter()) { 1410 1410 checkConcept<concepts::WriteMap<Edge, typename Map::Value>, Map>(); 1411 _reader_bits::MapStorageBase<Edge>* storage = 1412 1411 _reader_bits::MapStorageBase<Edge>* storage = 1412 new _reader_bits::MapStorage<Edge, Map, Converter>(map, converter); 1413 1413 _edge_maps.push_back(std::make_pair(caption, storage)); 1414 1414 return *this; … … 1421 1421 GraphReader& arcMap(const std::string& caption, Map& map) { 1422 1422 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>(); 1423 _reader_bits::MapStorageBase<Edge>* forward_storage = 1424 1423 _reader_bits::MapStorageBase<Edge>* forward_storage = 1424 new _reader_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map); 1425 1425 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage)); 1426 _reader_bits::MapStorageBase<Edge>* backward_storage = 1427 1426 _reader_bits::MapStorageBase<Edge>* backward_storage = 1427 new _reader_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map); 1428 1428 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage)); 1429 1429 return *this; … … 1435 1435 /// reader. 1436 1436 template <typename Map, typename Converter> 1437 GraphReader& arcMap(const std::string& caption, Map& map, 1438 1437 GraphReader& arcMap(const std::string& caption, Map& map, 1438 const Converter& converter = Converter()) { 1439 1439 checkConcept<concepts::WriteMap<Arc, typename Map::Value>, Map>(); 1440 _reader_bits::MapStorageBase<Edge>* forward_storage = 1441 1442 1440 _reader_bits::MapStorageBase<Edge>* forward_storage = 1441 new _reader_bits::GraphArcMapStorage<Graph, true, Map, Converter> 1442 (_graph, map, converter); 1443 1443 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage)); 1444 _reader_bits::MapStorageBase<Edge>* backward_storage = 1445 1446 1444 _reader_bits::MapStorageBase<Edge>* backward_storage = 1445 new _reader_bits::GraphArcMapStorage<Graph, false, Map, Converter> 1446 (_graph, map, converter); 1447 1447 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage)); 1448 1448 return *this; … … 1454 1454 template <typename Value> 1455 1455 GraphReader& attribute(const std::string& caption, Value& value) { 1456 _reader_bits::ValueStorageBase* storage = 1457 1456 _reader_bits::ValueStorageBase* storage = 1457 new _reader_bits::ValueStorage<Value>(value); 1458 1458 _attributes.insert(std::make_pair(caption, storage)); 1459 1459 return *this; … … 1465 1465 /// reader. 1466 1466 template <typename Value, typename Converter> 1467 GraphReader& attribute(const std::string& caption, Value& value, 1468 1469 _reader_bits::ValueStorageBase* storage = 1470 1467 GraphReader& attribute(const std::string& caption, Value& value, 1468 const Converter& converter = Converter()) { 1469 _reader_bits::ValueStorageBase* storage = 1470 new _reader_bits::ValueStorage<Value, Converter>(value, converter); 1471 1471 _attributes.insert(std::make_pair(caption, storage)); 1472 1472 return *this; … … 1479 1479 typedef _reader_bits::MapLookUpConverter<Node> Converter; 1480 1480 Converter converter(_node_index); 1481 _reader_bits::ValueStorageBase* storage = 1482 1481 _reader_bits::ValueStorageBase* storage = 1482 new _reader_bits::ValueStorage<Node, Converter>(node, converter); 1483 1483 _attributes.insert(std::make_pair(caption, storage)); 1484 1484 return *this; … … 1491 1491 typedef _reader_bits::MapLookUpConverter<Edge> Converter; 1492 1492 Converter converter(_edge_index); 1493 _reader_bits::ValueStorageBase* storage = 1494 1493 _reader_bits::ValueStorageBase* storage = 1494 new _reader_bits::ValueStorage<Edge, Converter>(edge, converter); 1495 1495 _attributes.insert(std::make_pair(caption, storage)); 1496 1496 return *this; … … 1503 1503 typedef _reader_bits::GraphArcLookUpConverter<Graph> Converter; 1504 1504 Converter converter(_graph, _edge_index); 1505 _reader_bits::ValueStorageBase* storage = 1506 1505 _reader_bits::ValueStorageBase* storage = 1506 new _reader_bits::ValueStorage<Arc, Converter>(arc, converter); 1507 1507 _attributes.insert(std::make_pair(caption, storage)); 1508 1508 return *this; … … 1550 1550 GraphReader& useNodes(const Map& map) { 1551 1551 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 1552 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 1552 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 1553 1553 _use_nodes = true; 1554 1554 _writer_bits::DefaultConverter<typename Map::Value> converter; 1555 1555 for (NodeIt n(_graph); n != INVALID; ++n) { 1556 1556 _node_index.insert(std::make_pair(converter(map[n]), n)); 1557 1557 } 1558 1558 return *this; … … 1565 1565 /// \c std::string. 1566 1566 template <typename Map, typename Converter> 1567 GraphReader& useNodes(const Map& map, 1568 1567 GraphReader& useNodes(const Map& map, 1568 const Converter& converter = Converter()) { 1569 1569 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 1570 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 1570 LEMON_ASSERT(!_use_nodes, "Multiple usage of useNodes() member"); 1571 1571 _use_nodes = true; 1572 1572 for (NodeIt n(_graph); n != INVALID; ++n) { 1573 1573 _node_index.insert(std::make_pair(converter(map[n]), n)); 1574 1574 } 1575 1575 return *this; … … 1587 1587 _writer_bits::DefaultConverter<typename Map::Value> converter; 1588 1588 for (EdgeIt a(_graph); a != INVALID; ++a) { 1589 1589 _edge_index.insert(std::make_pair(converter(map[a]), a)); 1590 1590 } 1591 1591 return *this; … … 1598 1598 /// \c std::string. 1599 1599 template <typename Map, typename Converter> 1600 GraphReader& useEdges(const Map& map, 1601 1600 GraphReader& useEdges(const Map& map, 1601 const Converter& converter = Converter()) { 1602 1602 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>(); 1603 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member"); 1603 LEMON_ASSERT(!_use_edges, "Multiple usage of useEdges() member"); 1604 1604 _use_edges = true; 1605 1605 for (EdgeIt a(_graph); a != INVALID; ++a) { 1606 1606 _edge_index.insert(std::make_pair(converter(map[a]), a)); 1607 1607 } 1608 1608 return *this; … … 1619 1619 /// \c useNodes() should be used to specify the label of the nodes. 1620 1620 GraphReader& skipNodes() { 1621 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set"); 1621 LEMON_ASSERT(!_skip_nodes, "Skip nodes already set"); 1622 1622 _skip_nodes = true; 1623 1623 return *this; … … 1630 1630 /// will not be constructed. 1631 1631 GraphReader& skipEdges() { 1632 LEMON_ASSERT(!_skip_edges, "Skip edges already set"); 1632 LEMON_ASSERT(!_skip_edges, "Skip edges already set"); 1633 1633 _skip_edges = true; 1634 1634 return *this; … … 1642 1642 std::string str; 1643 1643 while(++line_num, std::getline(*_is, str)) { 1644 1645 1646 1647 1648 1649 1644 line.clear(); line.str(str); 1645 char c; 1646 if (line >> std::ws >> c && c != '#') { 1647 line.putback(c); 1648 return true; 1649 } 1650 1650 } 1651 1651 return false; … … 1655 1655 return static_cast<bool>(*_is); 1656 1656 } 1657 1657 1658 1658 void skipSection() { 1659 1659 char c; 1660 1660 while (readSuccess() && line >> c && c != '@') { 1661 1661 readLine(); 1662 1662 } 1663 1663 line.putback(c); … … 1671 1671 char c; 1672 1672 if (!readLine() || !(line >> c) || c == '@') { 1673 1674 if (!_node_maps.empty()) 1675 1676 1673 if (readSuccess() && line) line.putback(c); 1674 if (!_node_maps.empty()) 1675 throw DataFormatError("Cannot find map names"); 1676 return; 1677 1677 } 1678 1678 line.putback(c); 1679 1679 1680 1680 { 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 std::map<std::string, int>::iterator jt = 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1681 std::map<std::string, int> maps; 1682 1683 std::string map; 1684 int index = 0; 1685 while (_reader_bits::readToken(line, map)) { 1686 if (maps.find(map) != maps.end()) { 1687 std::ostringstream msg; 1688 msg << "Multiple occurence of node map: " << map; 1689 throw DataFormatError(msg.str().c_str()); 1690 } 1691 maps.insert(std::make_pair(map, index)); 1692 ++index; 1693 } 1694 1695 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) { 1696 std::map<std::string, int>::iterator jt = 1697 maps.find(_node_maps[i].first); 1698 if (jt == maps.end()) { 1699 std::ostringstream msg; 1700 msg << "Map not found in file: " << _node_maps[i].first; 1701 throw DataFormatError(msg.str().c_str()); 1702 } 1703 map_index[i] = jt->second; 1704 } 1705 1706 { 1707 std::map<std::string, int>::iterator jt = maps.find("label"); 1708 if (jt != maps.end()) { 1709 label_index = jt->second; 1710 } else { 1711 label_index = -1; 1712 } 1713 } 1714 map_num = maps.size(); 1715 1715 } 1716 1716 1717 1717 while (readLine() && line >> c && c != '@') { 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 if (label_index != -1) 1735 1736 1737 if (label_index == -1) 1738 1739 1740 1741 1742 1743 1744 throw DataFormatError(msg.str().c_str()); 1745 1746 1747 1748 1749 1750 1751 1718 line.putback(c); 1719 1720 std::vector<std::string> tokens(map_num); 1721 for (int i = 0; i < map_num; ++i) { 1722 if (!_reader_bits::readToken(line, tokens[i])) { 1723 std::ostringstream msg; 1724 msg << "Column not found (" << i + 1 << ")"; 1725 throw DataFormatError(msg.str().c_str()); 1726 } 1727 } 1728 if (line >> std::ws >> c) 1729 throw DataFormatError("Extra character on the end of line"); 1730 1731 Node n; 1732 if (!_use_nodes) { 1733 n = _graph.addNode(); 1734 if (label_index != -1) 1735 _node_index.insert(std::make_pair(tokens[label_index], n)); 1736 } else { 1737 if (label_index == -1) 1738 throw DataFormatError("Label map not found in file"); 1739 typename std::map<std::string, Node>::iterator it = 1740 _node_index.find(tokens[label_index]); 1741 if (it == _node_index.end()) { 1742 std::ostringstream msg; 1743 msg << "Node with label not found: " << tokens[label_index]; 1744 throw DataFormatError(msg.str().c_str()); 1745 } 1746 n = it->second; 1747 } 1748 1749 for (int i = 0; i < static_cast<int>(_node_maps.size()); ++i) { 1750 _node_maps[i].second->set(n, tokens[map_index[i]]); 1751 } 1752 1752 1753 1753 } 1754 1754 if (readSuccess()) { 1755 1755 line.putback(c); 1756 1756 } 1757 1757 } … … 1764 1764 char c; 1765 1765 if (!readLine() || !(line >> c) || c == '@') { 1766 1767 if (!_edge_maps.empty()) 1768 1769 1766 if (readSuccess() && line) line.putback(c); 1767 if (!_edge_maps.empty()) 1768 throw DataFormatError("Cannot find map names"); 1769 return; 1770 1770 } 1771 1771 line.putback(c); 1772 1772 1773 1773 { 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 std::map<std::string, int>::iterator jt = 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1774 std::map<std::string, int> maps; 1775 1776 std::string map; 1777 int index = 0; 1778 while (_reader_bits::readToken(line, map)) { 1779 if (maps.find(map) != maps.end()) { 1780 std::ostringstream msg; 1781 msg << "Multiple occurence of edge map: " << map; 1782 throw DataFormatError(msg.str().c_str()); 1783 } 1784 maps.insert(std::make_pair(map, index)); 1785 ++index; 1786 } 1787 1788 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) { 1789 std::map<std::string, int>::iterator jt = 1790 maps.find(_edge_maps[i].first); 1791 if (jt == maps.end()) { 1792 std::ostringstream msg; 1793 msg << "Map not found in file: " << _edge_maps[i].first; 1794 throw DataFormatError(msg.str().c_str()); 1795 } 1796 map_index[i] = jt->second; 1797 } 1798 1799 { 1800 std::map<std::string, int>::iterator jt = maps.find("label"); 1801 if (jt != maps.end()) { 1802 label_index = jt->second; 1803 } else { 1804 label_index = -1; 1805 } 1806 } 1807 map_num = maps.size(); 1808 1808 } 1809 1809 1810 1810 while (readLine() && line >> c && c != '@') { 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1811 line.putback(c); 1812 1813 std::string source_token; 1814 std::string target_token; 1815 1816 if (!_reader_bits::readToken(line, source_token)) 1817 throw DataFormatError("Node u not found"); 1818 1819 if (!_reader_bits::readToken(line, target_token)) 1820 throw DataFormatError("Node v not found"); 1821 1822 std::vector<std::string> tokens(map_num); 1823 for (int i = 0; i < map_num; ++i) { 1824 if (!_reader_bits::readToken(line, tokens[i])) { 1825 std::ostringstream msg; 1826 msg << "Column not found (" << i + 1 << ")"; 1827 throw DataFormatError(msg.str().c_str()); 1828 } 1829 } 1830 if (line >> std::ws >> c) 1831 throw DataFormatError("Extra character on the end of line"); 1832 1833 Edge e; 1834 if (!_use_edges) { 1835 1835 1836 1836 typename NodeIndex::iterator it; 1837 1837 1838 1838 it = _node_index.find(source_token); 1839 1839 if (it == _node_index.end()) { … … 1845 1845 1846 1846 it = _node_index.find(target_token); 1847 if (it == _node_index.end()) { 1848 std::ostringstream msg; 1847 if (it == _node_index.end()) { 1848 std::ostringstream msg; 1849 1849 msg << "Item not found: " << target_token; 1850 1850 throw DataFormatError(msg.str().c_str()); 1851 } 1852 Node target = it->second; 1853 1854 1855 if (label_index != -1) 1856 1857 1858 if (label_index == -1) 1859 1860 1861 1862 1863 1864 1865 throw DataFormatError(msg.str().c_str()); 1866 1867 1868 1869 1870 1871 1872 1851 } 1852 Node target = it->second; 1853 1854 e = _graph.addEdge(source, target); 1855 if (label_index != -1) 1856 _edge_index.insert(std::make_pair(tokens[label_index], e)); 1857 } else { 1858 if (label_index == -1) 1859 throw DataFormatError("Label map not found in file"); 1860 typename std::map<std::string, Edge>::iterator it = 1861 _edge_index.find(tokens[label_index]); 1862 if (it == _edge_index.end()) { 1863 std::ostringstream msg; 1864 msg << "Edge with label not found: " << tokens[label_index]; 1865 throw DataFormatError(msg.str().c_str()); 1866 } 1867 e = it->second; 1868 } 1869 1870 for (int i = 0; i < static_cast<int>(_edge_maps.size()); ++i) { 1871 _edge_maps[i].second->set(e, tokens[map_index[i]]); 1872 } 1873 1873 1874 1874 } 1875 1875 if (readSuccess()) { 1876 1876 line.putback(c); 1877 1877 } 1878 1878 } … … 1884 1884 char c; 1885 1885 while (readLine() && line >> c && c != '@') { 1886 1887 1888 1889 1890 1891 1892 1893 1894 throw DataFormatError("Extra character on the end of line"); 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1886 line.putback(c); 1887 1888 std::string attr, token; 1889 if (!_reader_bits::readToken(line, attr)) 1890 throw DataFormatError("Attribute name not found"); 1891 if (!_reader_bits::readToken(line, token)) 1892 throw DataFormatError("Attribute value not found"); 1893 if (line >> c) 1894 throw DataFormatError("Extra character on the end of line"); 1895 1896 { 1897 std::set<std::string>::iterator it = read_attr.find(attr); 1898 if (it != read_attr.end()) { 1899 std::ostringstream msg; 1900 msg << "Multiple occurence of attribute " << attr; 1901 throw DataFormatError(msg.str().c_str()); 1902 } 1903 read_attr.insert(attr); 1904 } 1905 1906 { 1907 typename Attributes::iterator it = _attributes.lower_bound(attr); 1908 while (it != _attributes.end() && it->first == attr) { 1909 it->second->set(token); 1910 ++it; 1911 } 1912 } 1913 1913 1914 1914 } 1915 1915 if (readSuccess()) { 1916 1916 line.putback(c); 1917 1917 } 1918 1918 for (typename Attributes::iterator it = _attributes.begin(); 1919 1920 1921 1922 1923 1924 } 1919 it != _attributes.end(); ++it) { 1920 if (read_attr.find(it->first) == read_attr.end()) { 1921 std::ostringstream msg; 1922 msg << "Attribute not found in file: " << it->first; 1923 throw DataFormatError(msg.str().c_str()); 1924 } 1925 1925 } 1926 1926 } … … 1928 1928 public: 1929 1929 1930 /// \name Execution of the reader 1930 /// \name Execution of the reader 1931 1931 /// @{ 1932 1932 … … 1935 1935 /// This function starts the batch processing 1936 1936 void run() { 1937 1937 1938 1938 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader"); 1939 1939 1940 1940 bool nodes_done = _skip_nodes; 1941 1941 bool edges_done = _skip_edges; 1942 1942 bool attributes_done = false; 1943 1943 1944 line_num = 0; 1944 line_num = 0; 1945 1945 readLine(); 1946 1946 skipSection(); 1947 1947 1948 1948 while (readSuccess()) { 1949 1950 1951 1952 1953 1954 1955 1956 if (line >> c) 1957 1958 1959 1960 1961 1962 1963 1964 } else if ((section == "edges" || section == "arcs") && 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 } 1949 try { 1950 char c; 1951 std::string section, caption; 1952 line >> c; 1953 _reader_bits::readToken(line, section); 1954 _reader_bits::readToken(line, caption); 1955 1956 if (line >> c) 1957 throw DataFormatError("Extra character on the end of line"); 1958 1959 if (section == "nodes" && !nodes_done) { 1960 if (_nodes_caption.empty() || _nodes_caption == caption) { 1961 readNodes(); 1962 nodes_done = true; 1963 } 1964 } else if ((section == "edges" || section == "arcs") && 1965 !edges_done) { 1966 if (_edges_caption.empty() || _edges_caption == caption) { 1967 readEdges(); 1968 edges_done = true; 1969 } 1970 } else if (section == "attributes" && !attributes_done) { 1971 if (_attributes_caption.empty() || _attributes_caption == caption) { 1972 readAttributes(); 1973 attributes_done = true; 1974 } 1975 } else { 1976 readLine(); 1977 skipSection(); 1978 } 1979 } catch (DataFormatError& error) { 1980 error.line(line_num); 1981 throw; 1982 } 1983 1983 } 1984 1984 1985 1985 if (!nodes_done) { 1986 1986 throw DataFormatError("Section @nodes not found"); 1987 1987 } 1988 1988 1989 1989 if (!edges_done) { 1990 1990 throw DataFormatError("Section @edges not found"); 1991 1991 } 1992 1992 1993 1993 if (!attributes_done && !_attributes.empty()) { 1994 1994 throw DataFormatError("Section @attributes not found"); 1995 1995 } 1996 1996 … … 1998 1998 1999 1999 /// @} 2000 2000 2001 2001 }; 2002 2002 2003 2003 /// \brief Return a \ref GraphReader class 2004 /// 2004 /// 2005 2005 /// This function just returns a \ref GraphReader class. 2006 2006 /// \relates GraphReader … … 2012 2012 2013 2013 /// \brief Return a \ref GraphReader class 2014 /// 2014 /// 2015 2015 /// This function just returns a \ref GraphReader class. 2016 2016 /// \relates GraphReader 2017 2017 template <typename Graph> 2018 GraphReader<Graph> graphReader(const std::string& fn, 2019 2018 GraphReader<Graph> graphReader(const std::string& fn, 2019 Graph& graph) { 2020 2020 GraphReader<Graph> tmp(fn, graph); 2021 2021 return tmp; … … 2023 2023 2024 2024 /// \brief Return a \ref GraphReader class 2025 /// 2025 /// 2026 2026 /// This function just returns a \ref GraphReader class. 2027 2027 /// \relates GraphReader … … 2037 2037 SectionReader sectionReader(const std::string& fn); 2038 2038 SectionReader sectionReader(const char* fn); 2039 2039 2040 2040 /// \ingroup lemon_io 2041 2041 /// 2042 2042 /// \brief Section reader class 2043 2043 /// 2044 /// In the \ref lgf-format "LGF" file extra sections can be placed, 2044 /// In the \ref lgf-format "LGF" file extra sections can be placed, 2045 2045 /// which contain any data in arbitrary format. Such sections can be 2046 /// read with this class. A reading rule can be added to the class 2046 /// read with this class. A reading rule can be added to the class 2047 2047 /// with two different functions. With the \c sectionLines() function a 2048 2048 /// functor can process the section line-by-line, while with the \c … … 2051 2051 class SectionReader { 2052 2052 private: 2053 2053 2054 2054 std::istream* _is; 2055 2055 bool local_is; … … 2067 2067 /// Construct a section reader, which reads from the given input 2068 2068 /// stream. 2069 SectionReader(std::istream& is) 2069 SectionReader(std::istream& is) 2070 2070 : _is(&is), local_is(false) {} 2071 2071 … … 2073 2073 /// 2074 2074 /// Construct a section reader, which reads from the given file. 2075 SectionReader(const std::string& fn) 2075 SectionReader(const std::string& fn) 2076 2076 : _is(new std::ifstream(fn.c_str())), local_is(true) {} 2077 2077 2078 2078 /// \brief Constructor 2079 2079 /// 2080 2080 /// Construct a section reader, which reads from the given file. 2081 SectionReader(const char* fn) 2081 SectionReader(const char* fn) 2082 2082 : _is(new std::ifstream(fn)), local_is(true) {} 2083 2083 2084 2084 /// \brief Destructor 2085 2085 ~SectionReader() { 2086 for (Sections::iterator it = _sections.begin(); 2087 2088 2086 for (Sections::iterator it = _sections.begin(); 2087 it != _sections.end(); ++it) { 2088 delete it->second; 2089 2089 } 2090 2090 2091 2091 if (local_is) { 2092 2092 delete _is; 2093 2093 } 2094 2094 … … 2101 2101 friend SectionReader sectionReader(const char* fn); 2102 2102 2103 SectionReader(SectionReader& other) 2103 SectionReader(SectionReader& other) 2104 2104 : _is(other._is), local_is(other.local_is) { 2105 2105 2106 2106 other._is = 0; 2107 2107 other.local_is = false; 2108 2108 2109 2109 _sections.swap(other._sections); 2110 2110 } 2111 2111 2112 2112 SectionReader& operator=(const SectionReader&); 2113 2113 … … 2149 2149 /// // ... 2150 2150 /// 2151 /// reader.sectionLines("numbers", NumberSection(vec)); 2151 /// reader.sectionLines("numbers", NumberSection(vec)); 2152 2152 ///\endcode 2153 2153 template <typename Functor> 2154 2154 SectionReader& sectionLines(const std::string& type, Functor functor) { 2155 2155 LEMON_ASSERT(!type.empty(), "Type is empty."); 2156 LEMON_ASSERT(_sections.find(type) == _sections.end(), 2157 2158 _sections.insert(std::make_pair(type, 2156 LEMON_ASSERT(_sections.find(type) == _sections.end(), 2157 "Multiple reading of section."); 2158 _sections.insert(std::make_pair(type, 2159 2159 new _reader_bits::LineSection<Functor>(functor))); 2160 2160 return *this; … … 2172 2172 SectionReader& sectionStream(const std::string& type, Functor functor) { 2173 2173 LEMON_ASSERT(!type.empty(), "Type is empty."); 2174 LEMON_ASSERT(_sections.find(type) == _sections.end(), 2175 2176 _sections.insert(std::make_pair(type, 2177 2178 return *this; 2179 } 2180 2174 LEMON_ASSERT(_sections.find(type) == _sections.end(), 2175 "Multiple reading of section."); 2176 _sections.insert(std::make_pair(type, 2177 new _reader_bits::StreamSection<Functor>(functor))); 2178 return *this; 2179 } 2180 2181 2181 /// @} 2182 2182 … … 2186 2186 std::string str; 2187 2187 while(++line_num, std::getline(*_is, str)) { 2188 2189 2190 2191 2192 2193 2188 line.clear(); line.str(str); 2189 char c; 2190 if (line >> std::ws >> c && c != '#') { 2191 line.putback(c); 2192 return true; 2193 } 2194 2194 } 2195 2195 return false; … … 2199 2199 return static_cast<bool>(*_is); 2200 2200 } 2201 2201 2202 2202 void skipSection() { 2203 2203 char c; 2204 2204 while (readSuccess() && line >> c && c != '@') { 2205 2205 readLine(); 2206 2206 } 2207 2207 line.putback(c); … … 2211 2211 2212 2212 2213 /// \name Execution of the reader 2213 /// \name Execution of the reader 2214 2214 /// @{ 2215 2215 … … 2218 2218 /// This function starts the batch processing. 2219 2219 void run() { 2220 2220 2221 2221 LEMON_ASSERT(_is != 0, "This reader assigned to an other reader"); 2222 2222 2223 2223 std::set<std::string> extra_sections; 2224 2224 2225 line_num = 0; 2225 line_num = 0; 2226 2226 readLine(); 2227 2227 skipSection(); 2228 2228 2229 2229 while (readSuccess()) { 2230 2231 2232 2233 2234 2235 2236 2237 if (line >> c) 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 } 2230 try { 2231 char c; 2232 std::string section, caption; 2233 line >> c; 2234 _reader_bits::readToken(line, section); 2235 _reader_bits::readToken(line, caption); 2236 2237 if (line >> c) 2238 throw DataFormatError("Extra character on the end of line"); 2239 2240 if (extra_sections.find(section) != extra_sections.end()) { 2241 std::ostringstream msg; 2242 msg << "Multiple occurence of section " << section; 2243 throw DataFormatError(msg.str().c_str()); 2244 } 2245 Sections::iterator it = _sections.find(section); 2246 if (it != _sections.end()) { 2247 extra_sections.insert(section); 2248 it->second->process(*_is, line_num); 2249 } 2250 readLine(); 2251 skipSection(); 2252 } catch (DataFormatError& error) { 2253 error.line(line_num); 2254 throw; 2255 } 2256 2256 } 2257 2257 for (Sections::iterator it = _sections.begin(); 2258 2259 2260 2261 2262 2263 2258 it != _sections.end(); ++it) { 2259 if (extra_sections.find(it->first) == extra_sections.end()) { 2260 std::ostringstream os; 2261 os << "Cannot find section: " << it->first; 2262 throw DataFormatError(os.str().c_str()); 2263 } 2264 2264 } 2265 2265 } 2266 2266 2267 2267 /// @} 2268 2268 2269 2269 }; 2270 2270 2271 2271 /// \brief Return a \ref SectionReader class 2272 /// 2272 /// 2273 2273 /// This function just returns a \ref SectionReader class. 2274 2274 /// \relates SectionReader … … 2279 2279 2280 2280 /// \brief Return a \ref SectionReader class 2281 /// 2281 /// 2282 2282 /// This function just returns a \ref SectionReader class. 2283 2283 /// \relates SectionReader … … 2288 2288 2289 2289 /// \brief Return a \ref SectionReader class 2290 /// 2290 /// 2291 2291 /// This function just returns a \ref SectionReader class. 2292 2292 /// \relates SectionReader … … 2298 2298 /// \ingroup lemon_io 2299 2299 /// 2300 /// \brief Reader for the contents of the \ref lgf-format "LGF" file 2300 /// \brief Reader for the contents of the \ref lgf-format "LGF" file 2301 2301 /// 2302 2302 /// This class can be used to read the sections, the map names and … … 2308 2308 /// reading the graph. 2309 2309 /// 2310 ///\code 2311 /// LgfContents contents("graph.lgf"); 2310 ///\code 2311 /// LgfContents contents("graph.lgf"); 2312 2312 /// contents.run(); 2313 2313 /// … … 2317 2317 /// return -1; 2318 2318 /// } 2319 /// std::cout << "The name of the default node section: " 2319 /// std::cout << "The name of the default node section: " 2320 2320 /// << contents.nodeSection(0) << std::endl; 2321 /// std::cout << "The number of the arc maps: " 2321 /// std::cout << "The number of the arc maps: " 2322 2322 /// << contents.arcMaps(0).size() << std::endl; 2323 /// std::cout << "The name of second arc map: " 2323 /// std::cout << "The name of second arc map: " 2324 2324 /// << contents.arcMaps(0)[1] << std::endl; 2325 2325 ///\endcode 2326 class LgfContents { 2326 class LgfContents { 2327 2327 private: 2328 2328 … … 2345 2345 int line_num; 2346 2346 std::istringstream line; 2347 2347 2348 2348 public: 2349 2349 … … 2352 2352 /// Construct an \e LGF contents reader, which reads from the given 2353 2353 /// input stream. 2354 LgfContents(std::istream& is) 2354 LgfContents(std::istream& is) 2355 2355 : _is(&is), local_is(false) {} 2356 2356 … … 2359 2359 /// Construct an \e LGF contents reader, which reads from the given 2360 2360 /// file. 2361 LgfContents(const std::string& fn) 2361 LgfContents(const std::string& fn) 2362 2362 : _is(new std::ifstream(fn.c_str())), local_is(true) {} 2363 2363 … … 2368 2368 LgfContents(const char* fn) 2369 2369 : _is(new std::ifstream(fn)), local_is(true) {} 2370 2370 2371 2371 /// \brief Destructor 2372 2372 ~LgfContents() { … … 2375 2375 2376 2376 private: 2377 2377 2378 2378 LgfContents(const LgfContents&); 2379 2379 LgfContents& operator=(const LgfContents&); … … 2392 2392 } 2393 2393 2394 /// \brief Returns the node section name at the given position. 2395 /// 2396 /// Returns the node section name at the given position. 2394 /// \brief Returns the node section name at the given position. 2395 /// 2396 /// Returns the node section name at the given position. 2397 2397 const std::string& nodeSection(int i) const { 2398 2398 return _node_sections[i]; … … 2408 2408 /// @} 2409 2409 2410 /// \name Arc/Edge sections 2410 /// \name Arc/Edge sections 2411 2411 /// @{ 2412 2412 … … 2419 2419 } 2420 2420 2421 /// \brief Returns the arc/edge section name at the given position. 2422 /// 2423 /// Returns the arc/edge section name at the given position. 2421 /// \brief Returns the arc/edge section name at the given position. 2422 /// 2423 /// Returns the arc/edge section name at the given position. 2424 2424 /// \note It is synonym of \c edgeSection(). 2425 2425 const std::string& arcSection(int i) const { … … 2448 2448 } 2449 2449 2450 /// \brief Returns the section name at the given position. 2451 /// 2452 /// Returns the section name at the given position. 2450 /// \brief Returns the section name at the given position. 2451 /// 2452 /// Returns the section name at the given position. 2453 2453 /// \note It is synonym of \c arcSection(). 2454 2454 const std::string& edgeSection(int i) const { … … 2466 2466 /// @} 2467 2467 2468 /// \name Attribute sections 2468 /// \name Attribute sections 2469 2469 /// @{ 2470 2470 … … 2476 2476 } 2477 2477 2478 /// \brief Returns the attribute section name at the given position. 2479 /// 2480 /// Returns the attribute section name at the given position. 2478 /// \brief Returns the attribute section name at the given position. 2479 /// 2480 /// Returns the attribute section name at the given position. 2481 2481 const std::string& attributeSectionNames(int i) const { 2482 2482 return _attribute_sections[i]; … … 2492 2492 /// @} 2493 2493 2494 /// \name Extra sections 2494 /// \name Extra sections 2495 2495 /// @{ 2496 2496 … … 2502 2502 } 2503 2503 2504 /// \brief Returns the extra section type at the given position. 2505 /// 2506 /// Returns the section type at the given position. 2504 /// \brief Returns the extra section type at the given position. 2505 /// 2506 /// Returns the section type at the given position. 2507 2507 const std::string& extraSection(int i) const { 2508 2508 return _extra_sections[i]; … … 2516 2516 std::string str; 2517 2517 while(++line_num, std::getline(*_is, str)) { 2518 2519 2520 2521 2522 2523 2518 line.clear(); line.str(str); 2519 char c; 2520 if (line >> std::ws >> c && c != '#') { 2521 line.putback(c); 2522 return true; 2523 } 2524 2524 } 2525 2525 return false; … … 2533 2533 char c; 2534 2534 while (readSuccess() && line >> c && c != '@') { 2535 2535 readLine(); 2536 2536 } 2537 2537 line.putback(c); … … 2541 2541 char c; 2542 2542 if (!readLine() || !(line >> c) || c == '@') { 2543 2544 2543 if (readSuccess() && line) line.putback(c); 2544 return; 2545 2545 } 2546 2546 line.putback(c); 2547 2547 std::string map; 2548 2548 while (_reader_bits::readToken(line, map)) { 2549 2549 maps.push_back(map); 2550 2550 } 2551 2551 } … … 2555 2555 char c; 2556 2556 while (readSuccess() && line >> c && c != '@') { 2557 2558 2559 2560 2561 2557 line.putback(c); 2558 std::string attr; 2559 _reader_bits::readToken(line, attr); 2560 attrs.push_back(attr); 2561 readLine(); 2562 2562 } 2563 2563 line.putback(c); … … 2566 2566 public: 2567 2567 2568 /// \name Execution of the contents reader 2568 /// \name Execution of the contents reader 2569 2569 /// @{ 2570 2570 … … 2579 2579 while (readSuccess()) { 2580 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2581 char c; 2582 line >> c; 2583 2584 std::string section, caption; 2585 _reader_bits::readToken(line, section); 2586 _reader_bits::readToken(line, caption); 2587 2588 if (section == "nodes") { 2589 _node_sections.push_back(caption); 2590 _node_maps.push_back(std::vector<std::string>()); 2591 readMaps(_node_maps.back()); 2592 readLine(); skipSection(); 2593 } else if (section == "arcs" || section == "edges") { 2594 _edge_sections.push_back(caption); 2595 _arc_sections.push_back(section == "arcs"); 2596 _edge_maps.push_back(std::vector<std::string>()); 2597 readMaps(_edge_maps.back()); 2598 readLine(); skipSection(); 2599 } else if (section == "attributes") { 2600 _attribute_sections.push_back(caption); 2601 _attributes.push_back(std::vector<std::string>()); 2602 readAttributes(_attributes.back()); 2603 } else { 2604 _extra_sections.push_back(section); 2605 readLine(); skipSection(); 2606 } 2607 2607 } 2608 2608 } 2609 2609 2610 2610 /// @} 2611 2611 2612 2612 }; 2613 2613 } -
lemon/lgf_writer.h
r201 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 44 44 struct DefaultConverter { 45 45 std::string operator()(const Value& value) { 46 47 48 46 std::ostringstream os; 47 os << value; 48 return os.str(); 49 49 } 50 50 }; … … 63 63 private: 64 64 const Map& _map; 65 65 66 66 public: 67 67 MapLess(const Map& map) : _map(map) {} 68 68 69 69 bool operator()(const Item& left, const Item& right) { 70 70 return _map[left] < _map[right]; 71 71 } 72 72 }; … … 82 82 const Graph& _graph; 83 83 const Map& _map; 84 84 85 85 public: 86 GraphArcMapLess(const Graph& graph, const Map& map) 87 86 GraphArcMapLess(const Graph& graph, const Map& map) 87 : _graph(graph), _map(map) {} 88 88 89 89 bool operator()(const Item& left, const Item& right) { 90 return _map[_graph.direct(left, _dir)] < 91 90 return _map[_graph.direct(left, _dir)] < 91 _map[_graph.direct(right, _dir)]; 92 92 } 93 93 }; 94 94 95 template <typename _Item> 95 template <typename _Item> 96 96 class MapStorageBase { 97 97 public: … … 106 106 }; 107 107 108 template <typename _Item, typename _Map, 109 108 template <typename _Item, typename _Map, 109 typename _Converter = DefaultConverter<typename _Map::Value> > 110 110 class MapStorage : public MapStorageBase<_Item> { 111 111 public: … … 113 113 typedef _Converter Converter; 114 114 typedef _Item Item; 115 115 116 116 private: 117 117 const Map& _map; … … 119 119 120 120 public: 121 MapStorage(const Map& map, const Converter& converter = Converter()) 122 121 MapStorage(const Map& map, const Converter& converter = Converter()) 122 : _map(map), _converter(converter) {} 123 123 virtual ~MapStorage() {} 124 124 125 125 virtual std::string get(const Item& item) { 126 126 return _converter(_map[item]); 127 127 } 128 128 virtual void sort(std::vector<Item>& items) { 129 130 129 MapLess<Map> less(_map); 130 std::sort(items.begin(), items.end(), less); 131 131 } 132 132 }; 133 133 134 template <typename _Graph, bool _dir, typename _Map, 135 134 template <typename _Graph, bool _dir, typename _Map, 135 typename _Converter = DefaultConverter<typename _Map::Value> > 136 136 class GraphArcMapStorage : public MapStorageBase<typename _Graph::Edge> { 137 137 public: … … 141 141 typedef typename Graph::Edge Item; 142 142 static const bool dir = _dir; 143 143 144 144 private: 145 145 const Graph& _graph; … … 148 148 149 149 public: 150 GraphArcMapStorage(const Graph& graph, const Map& map, 151 const Converter& converter = Converter()) 152 150 GraphArcMapStorage(const Graph& graph, const Map& map, 151 const Converter& converter = Converter()) 152 : _graph(graph), _map(map), _converter(converter) {} 153 153 virtual ~GraphArcMapStorage() {} 154 154 155 155 virtual std::string get(const Item& item) { 156 156 return _converter(_map[_graph.direct(item, dir)]); 157 157 } 158 158 virtual void sort(std::vector<Item>& items) { 159 160 159 GraphArcMapLess<Graph, dir, Map> less(_graph, _map); 160 std::sort(items.begin(), items.end(), less); 161 161 } 162 162 }; … … 167 167 virtual ~ValueStorageBase() {} 168 168 169 virtual std::string get() = 0; 169 virtual std::string get() = 0; 170 170 }; 171 171 … … 182 182 public: 183 183 ValueStorage(const Value& value, const Converter& converter = Converter()) 184 184 : _value(value), _converter(converter) {} 185 185 186 186 virtual std::string get() { 187 187 return _converter(_value); 188 188 } 189 189 }; … … 192 192 struct MapLookUpConverter { 193 193 const std::map<Value, std::string>& _map; 194 195 MapLookUpConverter(const std::map<Value, std::string>& map) 196 197 194 195 MapLookUpConverter(const std::map<Value, std::string>& map) 196 : _map(map) {} 197 198 198 std::string operator()(const Value& str) { 199 typename std::map<Value, std::string>::const_iterator it = 200 201 202 203 204 199 typename std::map<Value, std::string>::const_iterator it = 200 _map.find(str); 201 if (it == _map.end()) { 202 throw DataFormatError("Item not found"); 203 } 204 return it->second; 205 205 } 206 206 }; … … 210 210 const Graph& _graph; 211 211 const std::map<typename Graph::Edge, std::string>& _map; 212 213 GraphArcLookUpConverter(const Graph& graph, 214 const std::map<typename Graph::Edge, 215 std::string>& map) 216 217 212 213 GraphArcLookUpConverter(const Graph& graph, 214 const std::map<typename Graph::Edge, 215 std::string>& map) 216 : _graph(graph), _map(map) {} 217 218 218 std::string operator()(const typename Graph::Arc& val) { 219 220 221 222 223 224 219 typename std::map<typename Graph::Edge, std::string> 220 ::const_iterator it = _map.find(val); 221 if (it == _map.end()) { 222 throw DataFormatError("Item not found"); 223 } 224 return (_graph.direction(val) ? '+' : '-') + it->second; 225 225 } 226 226 }; 227 227 228 228 inline bool isWhiteSpace(char c) { 229 return c == ' ' || c == '\t' || c == '\v' || 230 c == '\n' || c == '\r' || c == '\f'; 229 return c == ' ' || c == '\t' || c == '\v' || 230 c == '\n' || c == '\r' || c == '\f'; 231 231 } 232 232 233 233 inline bool isEscaped(char c) { 234 return c == '\\' || c == '\"' || c == '\'' || 235 234 return c == '\\' || c == '\"' || c == '\'' || 235 c == '\a' || c == '\b'; 236 236 } 237 237 … … 239 239 switch (c) { 240 240 case '\\': 241 242 241 os << "\\\\"; 242 return; 243 243 case '\"': 244 245 244 os << "\\\""; 245 return; 246 246 case '\a': 247 248 247 os << "\\a"; 248 return; 249 249 case '\b': 250 251 250 os << "\\b"; 251 return; 252 252 case '\f': 253 254 253 os << "\\f"; 254 return; 255 255 case '\r': 256 257 256 os << "\\r"; 257 return; 258 258 case '\n': 259 260 259 os << "\\n"; 260 return; 261 261 case '\t': 262 263 262 os << "\\t"; 263 return; 264 264 case '\v': 265 266 265 os << "\\v"; 266 return; 267 267 default: 268 269 270 271 272 273 274 275 276 } 268 if (c < 0x20) { 269 std::ios::fmtflags flags = os.flags(); 270 os << '\\' << std::oct << static_cast<int>(c); 271 os.flags(flags); 272 } else { 273 os << c; 274 } 275 return; 276 } 277 277 } 278 278 … … 282 282 char c; 283 283 while (is.get(c)) { 284 285 286 284 if (isWhiteSpace(c) || isEscaped(c)) { 285 return true; 286 } 287 287 } 288 288 return false; 289 289 } 290 290 291 291 inline std::ostream& writeToken(std::ostream& os, const std::string& str) { 292 292 293 293 if (requireEscape(str)) { 294 295 for (std::string::const_iterator it = str.begin(); 296 297 298 } 299 294 os << '\"'; 295 for (std::string::const_iterator it = str.begin(); 296 it != str.end(); ++it) { 297 writeEscape(os, *it); 298 } 299 os << '\"'; 300 300 } else { 301 301 os << str; 302 302 } 303 303 return os; … … 310 310 311 311 template <typename Digraph> 312 DigraphWriter<Digraph> digraphWriter(std::ostream& os, 313 312 DigraphWriter<Digraph> digraphWriter(std::ostream& os, 313 const Digraph& digraph); 314 314 315 315 template <typename Digraph> 316 DigraphWriter<Digraph> digraphWriter(const std::string& fn, 317 316 DigraphWriter<Digraph> digraphWriter(const std::string& fn, 317 const Digraph& digraph); 318 318 319 319 template <typename Digraph> 320 DigraphWriter<Digraph> digraphWriter(const char *fn, 321 322 320 DigraphWriter<Digraph> digraphWriter(const char *fn, 321 const Digraph& digraph); 322 323 323 /// \ingroup lemon_io 324 /// 324 /// 325 325 /// \brief \ref lgf-format "LGF" writer for directed graphs 326 326 /// … … 371 371 typedef _Digraph Digraph; 372 372 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph); 373 373 374 374 private: 375 375 … … 383 383 std::string _arcs_caption; 384 384 std::string _attributes_caption; 385 385 386 386 typedef std::map<Node, std::string> NodeIndex; 387 387 NodeIndex _node_index; … … 389 389 ArcIndex _arc_index; 390 390 391 typedef std::vector<std::pair<std::string, 392 _writer_bits::MapStorageBase<Node>* > > NodeMaps; 393 NodeMaps _node_maps; 394 395 typedef std::vector<std::pair<std::string, 391 typedef std::vector<std::pair<std::string, 392 _writer_bits::MapStorageBase<Node>* > > NodeMaps; 393 NodeMaps _node_maps; 394 395 typedef std::vector<std::pair<std::string, 396 396 _writer_bits::MapStorageBase<Arc>* > >ArcMaps; 397 397 ArcMaps _arc_maps; 398 398 399 typedef std::vector<std::pair<std::string, 399 typedef std::vector<std::pair<std::string, 400 400 _writer_bits::ValueStorageBase*> > Attributes; 401 401 Attributes _attributes; … … 410 410 /// Construct a directed graph writer, which writes to the given 411 411 /// output stream. 412 DigraphWriter(std::ostream& is, const Digraph& digraph) 412 DigraphWriter(std::ostream& is, const Digraph& digraph) 413 413 : _os(&is), local_os(false), _digraph(digraph), 414 414 _skip_nodes(false), _skip_arcs(false) {} 415 415 416 416 /// \brief Constructor … … 418 418 /// Construct a directed graph writer, which writes to the given 419 419 /// output file. 420 DigraphWriter(const std::string& fn, const Digraph& digraph) 420 DigraphWriter(const std::string& fn, const Digraph& digraph) 421 421 : _os(new std::ofstream(fn.c_str())), local_os(true), _digraph(digraph), 422 422 _skip_nodes(false), _skip_arcs(false) {} 423 423 424 424 /// \brief Constructor … … 426 426 /// Construct a directed graph writer, which writes to the given 427 427 /// output file. 428 DigraphWriter(const char* fn, const Digraph& digraph) 428 DigraphWriter(const char* fn, const Digraph& digraph) 429 429 : _os(new std::ofstream(fn)), local_os(true), _digraph(digraph), 430 430 _skip_nodes(false), _skip_arcs(false) {} 431 431 432 432 /// \brief Destructor 433 433 ~DigraphWriter() { 434 for (typename NodeMaps::iterator it = _node_maps.begin(); 435 436 437 } 438 439 for (typename ArcMaps::iterator it = _arc_maps.begin(); 440 441 442 } 443 444 for (typename Attributes::iterator it = _attributes.begin(); 445 446 434 for (typename NodeMaps::iterator it = _node_maps.begin(); 435 it != _node_maps.end(); ++it) { 436 delete it->second; 437 } 438 439 for (typename ArcMaps::iterator it = _arc_maps.begin(); 440 it != _arc_maps.end(); ++it) { 441 delete it->second; 442 } 443 444 for (typename Attributes::iterator it = _attributes.begin(); 445 it != _attributes.end(); ++it) { 446 delete it->second; 447 447 } 448 448 449 449 if (local_os) { 450 450 delete _os; 451 451 } 452 452 } … … 454 454 private: 455 455 456 friend DigraphWriter<Digraph> digraphWriter<>(std::ostream& os, 457 458 friend DigraphWriter<Digraph> digraphWriter<>(const std::string& fn, 459 const Digraph& digraph); 460 friend DigraphWriter<Digraph> digraphWriter<>(const char *fn, 461 462 463 DigraphWriter(DigraphWriter& other) 456 friend DigraphWriter<Digraph> digraphWriter<>(std::ostream& os, 457 const Digraph& digraph); 458 friend DigraphWriter<Digraph> digraphWriter<>(const std::string& fn, 459 const Digraph& digraph); 460 friend DigraphWriter<Digraph> digraphWriter<>(const char *fn, 461 const Digraph& digraph); 462 463 DigraphWriter(DigraphWriter& other) 464 464 : _os(other._os), local_os(other.local_os), _digraph(other._digraph), 465 465 _skip_nodes(other._skip_nodes), _skip_arcs(other._skip_arcs) { 466 466 467 467 other._os = 0; … … 479 479 _attributes_caption = other._attributes_caption; 480 480 } 481 481 482 482 DigraphWriter& operator=(const DigraphWriter&); 483 483 … … 486 486 /// \name Writing rules 487 487 /// @{ 488 488 489 489 /// \brief Node map writing rule 490 490 /// … … 493 493 DigraphWriter& nodeMap(const std::string& caption, const Map& map) { 494 494 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 495 _writer_bits::MapStorageBase<Node>* storage = 496 495 _writer_bits::MapStorageBase<Node>* storage = 496 new _writer_bits::MapStorage<Node, Map>(map); 497 497 _node_maps.push_back(std::make_pair(caption, storage)); 498 498 return *this; … … 504 504 /// writer. 505 505 template <typename Map, typename Converter> 506 DigraphWriter& nodeMap(const std::string& caption, const Map& map, 507 506 DigraphWriter& nodeMap(const std::string& caption, const Map& map, 507 const Converter& converter = Converter()) { 508 508 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 509 _writer_bits::MapStorageBase<Node>* storage = 510 509 _writer_bits::MapStorageBase<Node>* storage = 510 new _writer_bits::MapStorage<Node, Map, Converter>(map, converter); 511 511 _node_maps.push_back(std::make_pair(caption, storage)); 512 512 return *this; … … 519 519 DigraphWriter& arcMap(const std::string& caption, const Map& map) { 520 520 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>(); 521 _writer_bits::MapStorageBase<Arc>* storage = 522 521 _writer_bits::MapStorageBase<Arc>* storage = 522 new _writer_bits::MapStorage<Arc, Map>(map); 523 523 _arc_maps.push_back(std::make_pair(caption, storage)); 524 524 return *this; … … 530 530 /// writer. 531 531 template <typename Map, typename Converter> 532 DigraphWriter& arcMap(const std::string& caption, const Map& map, 533 532 DigraphWriter& arcMap(const std::string& caption, const Map& map, 533 const Converter& converter = Converter()) { 534 534 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>(); 535 _writer_bits::MapStorageBase<Arc>* storage = 536 535 _writer_bits::MapStorageBase<Arc>* storage = 536 new _writer_bits::MapStorage<Arc, Map, Converter>(map, converter); 537 537 _arc_maps.push_back(std::make_pair(caption, storage)); 538 538 return *this; … … 544 544 template <typename Value> 545 545 DigraphWriter& attribute(const std::string& caption, const Value& value) { 546 _writer_bits::ValueStorageBase* storage = 547 546 _writer_bits::ValueStorageBase* storage = 547 new _writer_bits::ValueStorage<Value>(value); 548 548 _attributes.push_back(std::make_pair(caption, storage)); 549 549 return *this; … … 555 555 /// writer. 556 556 template <typename Value, typename Converter> 557 DigraphWriter& attribute(const std::string& caption, const Value& value, 558 559 _writer_bits::ValueStorageBase* storage = 560 557 DigraphWriter& attribute(const std::string& caption, const Value& value, 558 const Converter& converter = Converter()) { 559 _writer_bits::ValueStorageBase* storage = 560 new _writer_bits::ValueStorage<Value, Converter>(value, converter); 561 561 _attributes.push_back(std::make_pair(caption, storage)); 562 562 return *this; … … 569 569 typedef _writer_bits::MapLookUpConverter<Node> Converter; 570 570 Converter converter(_node_index); 571 _writer_bits::ValueStorageBase* storage = 572 571 _writer_bits::ValueStorageBase* storage = 572 new _writer_bits::ValueStorage<Node, Converter>(node, converter); 573 573 _attributes.push_back(std::make_pair(caption, storage)); 574 574 return *this; … … 581 581 typedef _writer_bits::MapLookUpConverter<Arc> Converter; 582 582 Converter converter(_arc_index); 583 _writer_bits::ValueStorageBase* storage = 584 583 _writer_bits::ValueStorageBase* storage = 584 new _writer_bits::ValueStorage<Arc, Converter>(arc, converter); 585 585 _attributes.push_back(std::make_pair(caption, storage)); 586 586 return *this; … … 642 642 _writer_bits::MapStorageBase<Node>* label = 0; 643 643 for (typename NodeMaps::iterator it = _node_maps.begin(); 644 644 it != _node_maps.end(); ++it) { 645 645 if (it->first == "label") { 646 647 648 646 label = it->second; 647 break; 648 } 649 649 } 650 650 651 651 *_os << "@nodes"; 652 652 if (!_nodes_caption.empty()) { 653 653 _writer_bits::writeToken(*_os << ' ', _nodes_caption); 654 654 } 655 655 *_os << std::endl; 656 656 657 657 if (label == 0) { 658 658 *_os << "label" << '\t'; 659 659 } 660 660 for (typename NodeMaps::iterator it = _node_maps.begin(); 661 662 661 it != _node_maps.end(); ++it) { 662 _writer_bits::writeToken(*_os, it->first) << '\t'; 663 663 } 664 664 *_os << std::endl; … … 666 666 std::vector<Node> nodes; 667 667 for (NodeIt n(_digraph); n != INVALID; ++n) { 668 669 } 670 668 nodes.push_back(n); 669 } 670 671 671 if (label == 0) { 672 673 674 672 IdMap<Digraph, Node> id_map(_digraph); 673 _writer_bits::MapLess<IdMap<Digraph, Node> > id_less(id_map); 674 std::sort(nodes.begin(), nodes.end(), id_less); 675 675 } else { 676 676 label->sort(nodes); 677 677 } 678 678 679 679 for (int i = 0; i < static_cast<int>(nodes.size()); ++i) { 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 680 Node n = nodes[i]; 681 if (label == 0) { 682 std::ostringstream os; 683 os << _digraph.id(n); 684 _writer_bits::writeToken(*_os, os.str()); 685 *_os << '\t'; 686 _node_index.insert(std::make_pair(n, os.str())); 687 } 688 for (typename NodeMaps::iterator it = _node_maps.begin(); 689 it != _node_maps.end(); ++it) { 690 std::string value = it->second->get(n); 691 _writer_bits::writeToken(*_os, value); 692 if (it->first == "label") { 693 _node_index.insert(std::make_pair(n, value)); 694 } 695 *_os << '\t'; 696 } 697 *_os << std::endl; 698 698 } 699 699 } … … 702 702 _writer_bits::MapStorageBase<Node>* label = 0; 703 703 for (typename NodeMaps::iterator it = _node_maps.begin(); 704 704 it != _node_maps.end(); ++it) { 705 705 if (it->first == "label") { 706 707 708 706 label = it->second; 707 break; 708 } 709 709 } 710 710 711 711 if (label == 0) { 712 713 714 715 _node_index.insert(std::make_pair(n, os.str())); 716 } 712 for (NodeIt n(_digraph); n != INVALID; ++n) { 713 std::ostringstream os; 714 os << _digraph.id(n); 715 _node_index.insert(std::make_pair(n, os.str())); 716 } 717 717 } else { 718 719 std::string value = label->get(n); 720 721 718 for (NodeIt n(_digraph); n != INVALID; ++n) { 719 std::string value = label->get(n); 720 _node_index.insert(std::make_pair(n, value)); 721 } 722 722 } 723 723 } … … 726 726 _writer_bits::MapStorageBase<Arc>* label = 0; 727 727 for (typename ArcMaps::iterator it = _arc_maps.begin(); 728 728 it != _arc_maps.end(); ++it) { 729 729 if (it->first == "label") { 730 731 732 730 label = it->second; 731 break; 732 } 733 733 } 734 734 735 735 *_os << "@arcs"; 736 736 if (!_arcs_caption.empty()) { 737 737 _writer_bits::writeToken(*_os << ' ', _arcs_caption); 738 738 } 739 739 *_os << std::endl; … … 741 741 *_os << '\t' << '\t'; 742 742 if (label == 0) { 743 743 *_os << "label" << '\t'; 744 744 } 745 745 for (typename ArcMaps::iterator it = _arc_maps.begin(); 746 747 746 it != _arc_maps.end(); ++it) { 747 _writer_bits::writeToken(*_os, it->first) << '\t'; 748 748 } 749 749 *_os << std::endl; … … 751 751 std::vector<Arc> arcs; 752 752 for (ArcIt n(_digraph); n != INVALID; ++n) { 753 754 } 755 753 arcs.push_back(n); 754 } 755 756 756 if (label == 0) { 757 758 759 757 IdMap<Digraph, Arc> id_map(_digraph); 758 _writer_bits::MapLess<IdMap<Digraph, Arc> > id_less(id_map); 759 std::sort(arcs.begin(), arcs.end(), id_less); 760 760 } else { 761 761 label->sort(arcs); 762 762 } 763 763 764 764 for (int i = 0; i < static_cast<int>(arcs.size()); ++i) { 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 765 Arc a = arcs[i]; 766 _writer_bits::writeToken(*_os, _node_index. 767 find(_digraph.source(a))->second); 768 *_os << '\t'; 769 _writer_bits::writeToken(*_os, _node_index. 770 find(_digraph.target(a))->second); 771 *_os << '\t'; 772 if (label == 0) { 773 std::ostringstream os; 774 os << _digraph.id(a); 775 _writer_bits::writeToken(*_os, os.str()); 776 *_os << '\t'; 777 _arc_index.insert(std::make_pair(a, os.str())); 778 } 779 for (typename ArcMaps::iterator it = _arc_maps.begin(); 780 it != _arc_maps.end(); ++it) { 781 std::string value = it->second->get(a); 782 _writer_bits::writeToken(*_os, value); 783 if (it->first == "label") { 784 _arc_index.insert(std::make_pair(a, value)); 785 } 786 *_os << '\t'; 787 } 788 *_os << std::endl; 789 789 } 790 790 } … … 793 793 _writer_bits::MapStorageBase<Arc>* label = 0; 794 794 for (typename ArcMaps::iterator it = _arc_maps.begin(); 795 795 it != _arc_maps.end(); ++it) { 796 796 if (it->first == "label") { 797 798 799 797 label = it->second; 798 break; 799 } 800 800 } 801 801 802 802 if (label == 0) { 803 804 805 806 _arc_index.insert(std::make_pair(a, os.str())); 807 } 803 for (ArcIt a(_digraph); a != INVALID; ++a) { 804 std::ostringstream os; 805 os << _digraph.id(a); 806 _arc_index.insert(std::make_pair(a, os.str())); 807 } 808 808 } else { 809 810 std::string value = label->get(a); 811 812 809 for (ArcIt a(_digraph); a != INVALID; ++a) { 810 std::string value = label->get(a); 811 _arc_index.insert(std::make_pair(a, value)); 812 } 813 813 } 814 814 } … … 818 818 *_os << "@attributes"; 819 819 if (!_attributes_caption.empty()) { 820 820 _writer_bits::writeToken(*_os << ' ', _attributes_caption); 821 821 } 822 822 *_os << std::endl; 823 823 for (typename Attributes::iterator it = _attributes.begin(); 824 825 826 827 828 } 829 } 830 824 it != _attributes.end(); ++it) { 825 _writer_bits::writeToken(*_os, it->first) << ' '; 826 _writer_bits::writeToken(*_os, it->second->get()); 827 *_os << std::endl; 828 } 829 } 830 831 831 public: 832 833 /// \name Execution of the writer 832 833 /// \name Execution of the writer 834 834 /// @{ 835 835 … … 839 839 void run() { 840 840 if (!_skip_nodes) { 841 841 writeNodes(); 842 842 } else { 843 844 } 845 if (!_skip_arcs) { 846 843 createNodeIndex(); 844 } 845 if (!_skip_arcs) { 846 writeArcs(); 847 847 } else { 848 848 createArcIndex(); 849 849 } 850 850 writeAttributes(); … … 862 862 863 863 /// \brief Return a \ref DigraphWriter class 864 /// 864 /// 865 865 /// This function just returns a \ref DigraphWriter class. 866 866 /// \relates DigraphWriter 867 867 template <typename Digraph> 868 DigraphWriter<Digraph> digraphWriter(std::ostream& os, 869 868 DigraphWriter<Digraph> digraphWriter(std::ostream& os, 869 const Digraph& digraph) { 870 870 DigraphWriter<Digraph> tmp(os, digraph); 871 871 return tmp; … … 873 873 874 874 /// \brief Return a \ref DigraphWriter class 875 /// 875 /// 876 876 /// This function just returns a \ref DigraphWriter class. 877 877 /// \relates DigraphWriter 878 878 template <typename Digraph> 879 DigraphWriter<Digraph> digraphWriter(const std::string& fn, 880 879 DigraphWriter<Digraph> digraphWriter(const std::string& fn, 880 const Digraph& digraph) { 881 881 DigraphWriter<Digraph> tmp(fn, digraph); 882 882 return tmp; … … 884 884 885 885 /// \brief Return a \ref DigraphWriter class 886 /// 886 /// 887 887 /// This function just returns a \ref DigraphWriter class. 888 888 /// \relates DigraphWriter 889 889 template <typename Digraph> 890 DigraphWriter<Digraph> digraphWriter(const char* fn, 891 890 DigraphWriter<Digraph> digraphWriter(const char* fn, 891 const Digraph& digraph) { 892 892 DigraphWriter<Digraph> tmp(fn, digraph); 893 893 return tmp; … … 898 898 899 899 template <typename Graph> 900 GraphWriter<Graph> graphWriter(std::ostream& os, const Graph& graph); 900 GraphWriter<Graph> graphWriter(std::ostream& os, const Graph& graph); 901 901 902 902 template <typename Graph> 903 GraphWriter<Graph> graphWriter(const std::string& fn, const Graph& graph); 903 GraphWriter<Graph> graphWriter(const std::string& fn, const Graph& graph); 904 904 905 905 template <typename Graph> 906 GraphWriter<Graph> graphWriter(const char *fn, const Graph& graph); 906 GraphWriter<Graph> graphWriter(const char *fn, const Graph& graph); 907 907 908 908 /// \ingroup lemon_io 909 /// 909 /// 910 910 /// \brief \ref lgf-format "LGF" writer for directed graphs 911 911 /// … … 927 927 typedef _Graph Graph; 928 928 TEMPLATE_GRAPH_TYPEDEFS(Graph); 929 929 930 930 private: 931 931 … … 939 939 std::string _edges_caption; 940 940 std::string _attributes_caption; 941 941 942 942 typedef std::map<Node, std::string> NodeIndex; 943 943 NodeIndex _node_index; … … 945 945 EdgeIndex _edge_index; 946 946 947 typedef std::vector<std::pair<std::string, 948 _writer_bits::MapStorageBase<Node>* > > NodeMaps; 949 NodeMaps _node_maps; 950 951 typedef std::vector<std::pair<std::string, 947 typedef std::vector<std::pair<std::string, 948 _writer_bits::MapStorageBase<Node>* > > NodeMaps; 949 NodeMaps _node_maps; 950 951 typedef std::vector<std::pair<std::string, 952 952 _writer_bits::MapStorageBase<Edge>* > >EdgeMaps; 953 953 EdgeMaps _edge_maps; 954 954 955 typedef std::vector<std::pair<std::string, 955 typedef std::vector<std::pair<std::string, 956 956 _writer_bits::ValueStorageBase*> > Attributes; 957 957 Attributes _attributes; … … 966 966 /// Construct a directed graph writer, which writes to the given 967 967 /// output stream. 968 GraphWriter(std::ostream& is, const Graph& graph) 968 GraphWriter(std::ostream& is, const Graph& graph) 969 969 : _os(&is), local_os(false), _graph(graph), 970 970 _skip_nodes(false), _skip_edges(false) {} 971 971 972 972 /// \brief Constructor … … 974 974 /// Construct a directed graph writer, which writes to the given 975 975 /// output file. 976 GraphWriter(const std::string& fn, const Graph& graph) 976 GraphWriter(const std::string& fn, const Graph& graph) 977 977 : _os(new std::ofstream(fn.c_str())), local_os(true), _graph(graph), 978 978 _skip_nodes(false), _skip_edges(false) {} 979 979 980 980 /// \brief Constructor … … 982 982 /// Construct a directed graph writer, which writes to the given 983 983 /// output file. 984 GraphWriter(const char* fn, const Graph& graph) 984 GraphWriter(const char* fn, const Graph& graph) 985 985 : _os(new std::ofstream(fn)), local_os(true), _graph(graph), 986 986 _skip_nodes(false), _skip_edges(false) {} 987 987 988 988 /// \brief Destructor 989 989 ~GraphWriter() { 990 for (typename NodeMaps::iterator it = _node_maps.begin(); 991 992 993 } 994 995 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 996 997 998 } 999 1000 for (typename Attributes::iterator it = _attributes.begin(); 1001 1002 990 for (typename NodeMaps::iterator it = _node_maps.begin(); 991 it != _node_maps.end(); ++it) { 992 delete it->second; 993 } 994 995 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 996 it != _edge_maps.end(); ++it) { 997 delete it->second; 998 } 999 1000 for (typename Attributes::iterator it = _attributes.begin(); 1001 it != _attributes.end(); ++it) { 1002 delete it->second; 1003 1003 } 1004 1004 1005 1005 if (local_os) { 1006 1007 } 1008 } 1009 1006 delete _os; 1007 } 1008 } 1009 1010 1010 private: 1011 1011 1012 friend GraphWriter<Graph> graphWriter<>(std::ostream& os, 1013 const Graph& graph); 1014 friend GraphWriter<Graph> graphWriter<>(const std::string& fn, 1015 const Graph& graph); 1016 friend GraphWriter<Graph> graphWriter<>(const char *fn, 1017 const Graph& graph); 1018 1019 GraphWriter(GraphWriter& other) 1012 friend GraphWriter<Graph> graphWriter<>(std::ostream& os, 1013 const Graph& graph); 1014 friend GraphWriter<Graph> graphWriter<>(const std::string& fn, 1015 const Graph& graph); 1016 friend GraphWriter<Graph> graphWriter<>(const char *fn, 1017 const Graph& graph); 1018 1019 GraphWriter(GraphWriter& other) 1020 1020 : _os(other._os), local_os(other.local_os), _graph(other._graph), 1021 1021 _skip_nodes(other._skip_nodes), _skip_edges(other._skip_edges) { 1022 1022 1023 1023 other._os = 0; … … 1042 1042 /// \name Writing rules 1043 1043 /// @{ 1044 1044 1045 1045 /// \brief Node map writing rule 1046 1046 /// … … 1049 1049 GraphWriter& nodeMap(const std::string& caption, const Map& map) { 1050 1050 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 1051 _writer_bits::MapStorageBase<Node>* storage = 1052 1051 _writer_bits::MapStorageBase<Node>* storage = 1052 new _writer_bits::MapStorage<Node, Map>(map); 1053 1053 _node_maps.push_back(std::make_pair(caption, storage)); 1054 1054 return *this; … … 1060 1060 /// writer. 1061 1061 template <typename Map, typename Converter> 1062 GraphWriter& nodeMap(const std::string& caption, const Map& map, 1063 1062 GraphWriter& nodeMap(const std::string& caption, const Map& map, 1063 const Converter& converter = Converter()) { 1064 1064 checkConcept<concepts::ReadMap<Node, typename Map::Value>, Map>(); 1065 _writer_bits::MapStorageBase<Node>* storage = 1066 1065 _writer_bits::MapStorageBase<Node>* storage = 1066 new _writer_bits::MapStorage<Node, Map, Converter>(map, converter); 1067 1067 _node_maps.push_back(std::make_pair(caption, storage)); 1068 1068 return *this; … … 1075 1075 GraphWriter& edgeMap(const std::string& caption, const Map& map) { 1076 1076 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>(); 1077 _writer_bits::MapStorageBase<Edge>* storage = 1078 1077 _writer_bits::MapStorageBase<Edge>* storage = 1078 new _writer_bits::MapStorage<Edge, Map>(map); 1079 1079 _edge_maps.push_back(std::make_pair(caption, storage)); 1080 1080 return *this; … … 1086 1086 /// writer. 1087 1087 template <typename Map, typename Converter> 1088 GraphWriter& edgeMap(const std::string& caption, const Map& map, 1089 1088 GraphWriter& edgeMap(const std::string& caption, const Map& map, 1089 const Converter& converter = Converter()) { 1090 1090 checkConcept<concepts::ReadMap<Edge, typename Map::Value>, Map>(); 1091 _writer_bits::MapStorageBase<Edge>* storage = 1092 1091 _writer_bits::MapStorageBase<Edge>* storage = 1092 new _writer_bits::MapStorage<Edge, Map, Converter>(map, converter); 1093 1093 _edge_maps.push_back(std::make_pair(caption, storage)); 1094 1094 return *this; … … 1101 1101 GraphWriter& arcMap(const std::string& caption, const Map& map) { 1102 1102 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>(); 1103 _writer_bits::MapStorageBase<Edge>* forward_storage = 1104 1103 _writer_bits::MapStorageBase<Edge>* forward_storage = 1104 new _writer_bits::GraphArcMapStorage<Graph, true, Map>(_graph, map); 1105 1105 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage)); 1106 _writer_bits::MapStorageBase<Edge>* backward_storage = 1107 1106 _writer_bits::MapStorageBase<Edge>* backward_storage = 1107 new _writer_bits::GraphArcMapStorage<Graph, false, Map>(_graph, map); 1108 1108 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage)); 1109 1109 return *this; … … 1115 1115 /// writer. 1116 1116 template <typename Map, typename Converter> 1117 GraphWriter& arcMap(const std::string& caption, const Map& map, 1118 1117 GraphWriter& arcMap(const std::string& caption, const Map& map, 1118 const Converter& converter = Converter()) { 1119 1119 checkConcept<concepts::ReadMap<Arc, typename Map::Value>, Map>(); 1120 _writer_bits::MapStorageBase<Edge>* forward_storage = 1121 1122 1120 _writer_bits::MapStorageBase<Edge>* forward_storage = 1121 new _writer_bits::GraphArcMapStorage<Graph, true, Map, Converter> 1122 (_graph, map, converter); 1123 1123 _edge_maps.push_back(std::make_pair('+' + caption, forward_storage)); 1124 _writer_bits::MapStorageBase<Edge>* backward_storage = 1125 1126 1124 _writer_bits::MapStorageBase<Edge>* backward_storage = 1125 new _writer_bits::GraphArcMapStorage<Graph, false, Map, Converter> 1126 (_graph, map, converter); 1127 1127 _edge_maps.push_back(std::make_pair('-' + caption, backward_storage)); 1128 1128 return *this; … … 1134 1134 template <typename Value> 1135 1135 GraphWriter& attribute(const std::string& caption, const Value& value) { 1136 _writer_bits::ValueStorageBase* storage = 1137 1136 _writer_bits::ValueStorageBase* storage = 1137 new _writer_bits::ValueStorage<Value>(value); 1138 1138 _attributes.push_back(std::make_pair(caption, storage)); 1139 1139 return *this; … … 1145 1145 /// writer. 1146 1146 template <typename Value, typename Converter> 1147 GraphWriter& attribute(const std::string& caption, const Value& value, 1148 1149 _writer_bits::ValueStorageBase* storage = 1150 1147 GraphWriter& attribute(const std::string& caption, const Value& value, 1148 const Converter& converter = Converter()) { 1149 _writer_bits::ValueStorageBase* storage = 1150 new _writer_bits::ValueStorage<Value, Converter>(value, converter); 1151 1151 _attributes.push_back(std::make_pair(caption, storage)); 1152 1152 return *this; … … 1159 1159 typedef _writer_bits::MapLookUpConverter<Node> Converter; 1160 1160 Converter converter(_node_index); 1161 _writer_bits::ValueStorageBase* storage = 1162 1161 _writer_bits::ValueStorageBase* storage = 1162 new _writer_bits::ValueStorage<Node, Converter>(node, converter); 1163 1163 _attributes.push_back(std::make_pair(caption, storage)); 1164 1164 return *this; … … 1171 1171 typedef _writer_bits::MapLookUpConverter<Edge> Converter; 1172 1172 Converter converter(_edge_index); 1173 _writer_bits::ValueStorageBase* storage = 1174 1173 _writer_bits::ValueStorageBase* storage = 1174 new _writer_bits::ValueStorage<Edge, Converter>(edge, converter); 1175 1175 _attributes.push_back(std::make_pair(caption, storage)); 1176 1176 return *this; … … 1183 1183 typedef _writer_bits::GraphArcLookUpConverter<Graph> Converter; 1184 1184 Converter converter(_graph, _edge_index); 1185 _writer_bits::ValueStorageBase* storage = 1186 1185 _writer_bits::ValueStorageBase* storage = 1186 new _writer_bits::ValueStorage<Arc, Converter>(arc, converter); 1187 1187 _attributes.push_back(std::make_pair(caption, storage)); 1188 1188 return *this; … … 1244 1244 _writer_bits::MapStorageBase<Node>* label = 0; 1245 1245 for (typename NodeMaps::iterator it = _node_maps.begin(); 1246 1246 it != _node_maps.end(); ++it) { 1247 1247 if (it->first == "label") { 1248 1249 1250 1248 label = it->second; 1249 break; 1250 } 1251 1251 } 1252 1252 1253 1253 *_os << "@nodes"; 1254 1254 if (!_nodes_caption.empty()) { 1255 1255 _writer_bits::writeToken(*_os << ' ', _nodes_caption); 1256 1256 } 1257 1257 *_os << std::endl; 1258 1258 1259 1259 if (label == 0) { 1260 1260 *_os << "label" << '\t'; 1261 1261 } 1262 1262 for (typename NodeMaps::iterator it = _node_maps.begin(); 1263 1264 1263 it != _node_maps.end(); ++it) { 1264 _writer_bits::writeToken(*_os, it->first) << '\t'; 1265 1265 } 1266 1266 *_os << std::endl; … … 1268 1268 std::vector<Node> nodes; 1269 1269 for (NodeIt n(_graph); n != INVALID; ++n) { 1270 1271 } 1272 1270 nodes.push_back(n); 1271 } 1272 1273 1273 if (label == 0) { 1274 1275 1276 1274 IdMap<Graph, Node> id_map(_graph); 1275 _writer_bits::MapLess<IdMap<Graph, Node> > id_less(id_map); 1276 std::sort(nodes.begin(), nodes.end(), id_less); 1277 1277 } else { 1278 1278 label->sort(nodes); 1279 1279 } 1280 1280 1281 1281 for (int i = 0; i < static_cast<int>(nodes.size()); ++i) { 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1282 Node n = nodes[i]; 1283 if (label == 0) { 1284 std::ostringstream os; 1285 os << _graph.id(n); 1286 _writer_bits::writeToken(*_os, os.str()); 1287 *_os << '\t'; 1288 _node_index.insert(std::make_pair(n, os.str())); 1289 } 1290 for (typename NodeMaps::iterator it = _node_maps.begin(); 1291 it != _node_maps.end(); ++it) { 1292 std::string value = it->second->get(n); 1293 _writer_bits::writeToken(*_os, value); 1294 if (it->first == "label") { 1295 _node_index.insert(std::make_pair(n, value)); 1296 } 1297 *_os << '\t'; 1298 } 1299 *_os << std::endl; 1300 1300 } 1301 1301 } … … 1304 1304 _writer_bits::MapStorageBase<Node>* label = 0; 1305 1305 for (typename NodeMaps::iterator it = _node_maps.begin(); 1306 1306 it != _node_maps.end(); ++it) { 1307 1307 if (it->first == "label") { 1308 1309 1310 1308 label = it->second; 1309 break; 1310 } 1311 1311 } 1312 1312 1313 1313 if (label == 0) { 1314 1315 1316 1317 _node_index.insert(std::make_pair(n, os.str())); 1318 } 1314 for (NodeIt n(_graph); n != INVALID; ++n) { 1315 std::ostringstream os; 1316 os << _graph.id(n); 1317 _node_index.insert(std::make_pair(n, os.str())); 1318 } 1319 1319 } else { 1320 1321 std::string value = label->get(n); 1322 1323 1320 for (NodeIt n(_graph); n != INVALID; ++n) { 1321 std::string value = label->get(n); 1322 _node_index.insert(std::make_pair(n, value)); 1323 } 1324 1324 } 1325 1325 } … … 1328 1328 _writer_bits::MapStorageBase<Edge>* label = 0; 1329 1329 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 1330 1330 it != _edge_maps.end(); ++it) { 1331 1331 if (it->first == "label") { 1332 1333 1334 1332 label = it->second; 1333 break; 1334 } 1335 1335 } 1336 1336 1337 1337 *_os << "@edges"; 1338 1338 if (!_edges_caption.empty()) { 1339 1339 _writer_bits::writeToken(*_os << ' ', _edges_caption); 1340 1340 } 1341 1341 *_os << std::endl; … … 1343 1343 *_os << '\t' << '\t'; 1344 1344 if (label == 0) { 1345 1345 *_os << "label" << '\t'; 1346 1346 } 1347 1347 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 1348 1349 1348 it != _edge_maps.end(); ++it) { 1349 _writer_bits::writeToken(*_os, it->first) << '\t'; 1350 1350 } 1351 1351 *_os << std::endl; … … 1353 1353 std::vector<Edge> edges; 1354 1354 for (EdgeIt n(_graph); n != INVALID; ++n) { 1355 1356 } 1357 1355 edges.push_back(n); 1356 } 1357 1358 1358 if (label == 0) { 1359 1360 1361 1359 IdMap<Graph, Edge> id_map(_graph); 1360 _writer_bits::MapLess<IdMap<Graph, Edge> > id_less(id_map); 1361 std::sort(edges.begin(), edges.end(), id_less); 1362 1362 } else { 1363 1363 label->sort(edges); 1364 1364 } 1365 1365 1366 1366 for (int i = 0; i < static_cast<int>(edges.size()); ++i) { 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1367 Edge e = edges[i]; 1368 _writer_bits::writeToken(*_os, _node_index. 1369 find(_graph.u(e))->second); 1370 *_os << '\t'; 1371 _writer_bits::writeToken(*_os, _node_index. 1372 find(_graph.v(e))->second); 1373 *_os << '\t'; 1374 if (label == 0) { 1375 std::ostringstream os; 1376 os << _graph.id(e); 1377 _writer_bits::writeToken(*_os, os.str()); 1378 *_os << '\t'; 1379 _edge_index.insert(std::make_pair(e, os.str())); 1380 } 1381 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 1382 it != _edge_maps.end(); ++it) { 1383 std::string value = it->second->get(e); 1384 _writer_bits::writeToken(*_os, value); 1385 if (it->first == "label") { 1386 _edge_index.insert(std::make_pair(e, value)); 1387 } 1388 *_os << '\t'; 1389 } 1390 *_os << std::endl; 1391 1391 } 1392 1392 } … … 1395 1395 _writer_bits::MapStorageBase<Edge>* label = 0; 1396 1396 for (typename EdgeMaps::iterator it = _edge_maps.begin(); 1397 1397 it != _edge_maps.end(); ++it) { 1398 1398 if (it->first == "label") { 1399 1400 1401 1399 label = it->second; 1400 break; 1401 } 1402 1402 } 1403 1403 1404 1404 if (label == 0) { 1405 1406 1407 1408 _edge_index.insert(std::make_pair(e, os.str())); 1409 } 1405 for (EdgeIt e(_graph); e != INVALID; ++e) { 1406 std::ostringstream os; 1407 os << _graph.id(e); 1408 _edge_index.insert(std::make_pair(e, os.str())); 1409 } 1410 1410 } else { 1411 1412 std::string value = label->get(e); 1413 1414 1411 for (EdgeIt e(_graph); e != INVALID; ++e) { 1412 std::string value = label->get(e); 1413 _edge_index.insert(std::make_pair(e, value)); 1414 } 1415 1415 } 1416 1416 } … … 1420 1420 *_os << "@attributes"; 1421 1421 if (!_attributes_caption.empty()) { 1422 1422 _writer_bits::writeToken(*_os << ' ', _attributes_caption); 1423 1423 } 1424 1424 *_os << std::endl; 1425 1425 for (typename Attributes::iterator it = _attributes.begin(); 1426 1427 1428 1429 1430 } 1431 } 1432 1426 it != _attributes.end(); ++it) { 1427 _writer_bits::writeToken(*_os, it->first) << ' '; 1428 _writer_bits::writeToken(*_os, it->second->get()); 1429 *_os << std::endl; 1430 } 1431 } 1432 1433 1433 public: 1434 1435 /// \name Execution of the writer 1434 1435 /// \name Execution of the writer 1436 1436 /// @{ 1437 1437 … … 1441 1441 void run() { 1442 1442 if (!_skip_nodes) { 1443 1443 writeNodes(); 1444 1444 } else { 1445 1446 } 1447 if (!_skip_edges) { 1448 1445 createNodeIndex(); 1446 } 1447 if (!_skip_edges) { 1448 writeEdges(); 1449 1449 } else { 1450 1450 createEdgeIndex(); 1451 1451 } 1452 1452 writeAttributes(); … … 1464 1464 1465 1465 /// \brief Return a \ref GraphWriter class 1466 /// 1466 /// 1467 1467 /// This function just returns a \ref GraphWriter class. 1468 1468 /// \relates GraphWriter … … 1474 1474 1475 1475 /// \brief Return a \ref GraphWriter class 1476 /// 1476 /// 1477 1477 /// This function just returns a \ref GraphWriter class. 1478 1478 /// \relates GraphWriter … … 1484 1484 1485 1485 /// \brief Return a \ref GraphWriter class 1486 /// 1486 /// 1487 1487 /// This function just returns a \ref GraphWriter class. 1488 1488 /// \relates GraphWriter -
lemon/list_graph.h
r184 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 38 38 int prev, next; 39 39 }; 40 40 41 41 struct ArcT { 42 42 int target, source; … … 54 54 55 55 int first_free_arc; 56 56 57 57 public: 58 58 59 59 typedef ListDigraphBase Digraph; 60 60 61 61 class Node { 62 62 friend class ListDigraphBase; … … 93 93 ListDigraphBase() 94 94 : nodes(), first_node(-1), 95 96 97 98 int maxNodeId() const { return nodes.size()-1; } 95 first_free_node(-1), arcs(), first_free_arc(-1) {} 96 97 98 int maxNodeId() const { return nodes.size()-1; } 99 99 int maxArcId() const { return arcs.size()-1; } 100 100 … … 103 103 104 104 105 void first(Node& node) const { 105 void first(Node& node) const { 106 106 node.id = first_node; 107 107 } … … 112 112 113 113 114 void first(Arc& arc) const { 114 void first(Arc& arc) const { 115 115 int n; 116 for(n = first_node; 117 n!=-1 && nodes[n].first_in == -1; 118 116 for(n = first_node; 117 n!=-1 && nodes[n].first_in == -1; 118 n = nodes[n].next) {} 119 119 arc.id = (n == -1) ? -1 : nodes[n].first_in; 120 120 } … … 122 122 void next(Arc& arc) const { 123 123 if (arcs[arc.id].next_in != -1) { 124 125 } else { 126 127 128 n!=-1 && nodes[n].first_in == -1; 129 130 131 } 124 arc.id = arcs[arc.id].next_in; 125 } else { 126 int n; 127 for(n = nodes[arcs[arc.id].target].next; 128 n!=-1 && nodes[n].first_in == -1; 129 n = nodes[n].next) {} 130 arc.id = (n == -1) ? -1 : nodes[n].first_in; 131 } 132 132 } 133 133 … … 146 146 } 147 147 148 148 149 149 static int id(Node v) { return v.id; } 150 150 static int id(Arc e) { return e.id; } … … 153 153 static Arc arcFromId(int id) { return Arc(id);} 154 154 155 bool valid(Node n) const { 156 return n.id >= 0 && n.id < static_cast<int>(nodes.size()) && 157 158 } 159 160 bool valid(Arc a) const { 161 return a.id >= 0 && a.id < static_cast<int>(arcs.size()) && 162 163 } 164 165 Node addNode() { 155 bool valid(Node n) const { 156 return n.id >= 0 && n.id < static_cast<int>(nodes.size()) && 157 nodes[n.id].prev != -2; 158 } 159 160 bool valid(Arc a) const { 161 return a.id >= 0 && a.id < static_cast<int>(arcs.size()) && 162 arcs[a.id].prev_in != -2; 163 } 164 165 Node addNode() { 166 166 int n; 167 167 168 168 if(first_free_node==-1) { 169 170 171 } else { 172 173 174 } 175 169 n = nodes.size(); 170 nodes.push_back(NodeT()); 171 } else { 172 n = first_free_node; 173 first_free_node = nodes[n].next; 174 } 175 176 176 nodes[n].next = first_node; 177 177 if(first_node != -1) nodes[first_node].prev = n; 178 178 first_node = n; 179 179 nodes[n].prev = -1; 180 180 181 181 nodes[n].first_in = nodes[n].first_out = -1; 182 182 183 183 return Node(n); 184 184 } 185 185 186 186 Arc addArc(Node u, Node v) { 187 int n; 187 int n; 188 188 189 189 if (first_free_arc == -1) { 190 191 192 } else { 193 194 195 } 196 197 arcs[n].source = u.id; 190 n = arcs.size(); 191 arcs.push_back(ArcT()); 192 } else { 193 n = first_free_arc; 194 first_free_arc = arcs[n].next_in; 195 } 196 197 arcs[n].source = u.id; 198 198 arcs[n].target = v.id; 199 199 200 200 arcs[n].next_out = nodes[u.id].first_out; 201 201 if(nodes[u.id].first_out != -1) { 202 203 } 204 202 arcs[nodes[u.id].first_out].prev_out = n; 203 } 204 205 205 arcs[n].next_in = nodes[v.id].first_in; 206 206 if(nodes[v.id].first_in != -1) { 207 208 } 209 207 arcs[nodes[v.id].first_in].prev_in = n; 208 } 209 210 210 arcs[n].prev_in = arcs[n].prev_out = -1; 211 211 212 212 nodes[u.id].first_out = nodes[v.id].first_in = n; 213 213 214 214 return Arc(n); 215 215 } 216 216 217 217 void erase(const Node& node) { 218 218 int n = node.id; 219 219 220 220 if(nodes[n].next != -1) { 221 222 } 223 221 nodes[nodes[n].next].prev = nodes[n].prev; 222 } 223 224 224 if(nodes[n].prev != -1) { 225 226 } else { 227 228 } 229 225 nodes[nodes[n].prev].next = nodes[n].next; 226 } else { 227 first_node = nodes[n].next; 228 } 229 230 230 nodes[n].next = first_free_node; 231 231 first_free_node = n; … … 233 233 234 234 } 235 235 236 236 void erase(const Arc& arc) { 237 237 int n = arc.id; 238 238 239 239 if(arcs[n].next_in!=-1) { 240 240 arcs[arcs[n].next_in].prev_in = arcs[n].prev_in; 241 241 } 242 242 243 243 if(arcs[n].prev_in!=-1) { 244 245 } else { 246 247 } 248 249 244 arcs[arcs[n].prev_in].next_in = arcs[n].next_in; 245 } else { 246 nodes[arcs[n].target].first_in = arcs[n].next_in; 247 } 248 249 250 250 if(arcs[n].next_out!=-1) { 251 252 } 251 arcs[arcs[n].next_out].prev_out = arcs[n].prev_out; 252 } 253 253 254 254 if(arcs[n].prev_out!=-1) { 255 256 } else { 257 258 } 259 255 arcs[arcs[n].prev_out].next_out = arcs[n].next_out; 256 } else { 257 nodes[arcs[n].source].first_out = arcs[n].next_out; 258 } 259 260 260 arcs[n].next_in = first_free_arc; 261 261 first_free_arc = n; … … 270 270 271 271 protected: 272 void changeTarget(Arc e, Node n) 272 void changeTarget(Arc e, Node n) 273 273 { 274 274 if(arcs[e.id].next_in != -1) 275 275 arcs[arcs[e.id].next_in].prev_in = arcs[e.id].prev_in; 276 276 if(arcs[e.id].prev_in != -1) 277 277 arcs[arcs[e.id].prev_in].next_in = arcs[e.id].next_in; 278 278 else nodes[arcs[e.id].target].first_in = arcs[e.id].next_in; 279 279 if (nodes[n.id].first_in != -1) { 280 280 arcs[nodes[n.id].first_in].prev_in = e.id; 281 281 } 282 282 arcs[e.id].target = n.id; … … 285 285 nodes[n.id].first_in = e.id; 286 286 } 287 void changeSource(Arc e, Node n) 287 void changeSource(Arc e, Node n) 288 288 { 289 289 if(arcs[e.id].next_out != -1) 290 290 arcs[arcs[e.id].next_out].prev_out = arcs[e.id].prev_out; 291 291 if(arcs[e.id].prev_out != -1) 292 292 arcs[arcs[e.id].prev_out].next_out = arcs[e.id].next_out; 293 293 else nodes[arcs[e.id].source].first_out = arcs[e.id].next_out; 294 294 if (nodes[n.id].first_out != -1) { 295 295 arcs[nodes[n.id].first_out].prev_out = e.id; 296 296 } 297 297 arcs[e.id].source = n.id; … … 308 308 /// @{ 309 309 310 ///A general directed graph structure. 311 312 ///\ref ListDigraph is a simple and fast <em>directed graph</em> 313 ///implementation based on static linked lists that are stored in 314 ///\c std::vector structures. 310 ///A general directed graph structure. 311 312 ///\ref ListDigraph is a simple and fast <em>directed graph</em> 313 ///implementation based on static linked lists that are stored in 314 ///\c std::vector structures. 315 315 /// 316 316 ///It conforms to the \ref concepts::Digraph "Digraph concept" and it … … 327 327 private: 328 328 ///ListDigraph is \e not copy constructible. Use copyDigraph() instead. 329 329 330 330 ///ListDigraph is \e not copy constructible. Use copyDigraph() instead. 331 331 /// … … 342 342 343 343 /// Constructor 344 344 345 345 /// Constructor. 346 346 /// … … 348 348 349 349 ///Add a new node to the digraph. 350 350 351 351 ///Add a new node to the digraph. 352 352 ///\return the new node. … … 354 354 355 355 ///Add a new arc to the digraph. 356 356 357 357 ///Add a new arc to the digraph with source node \c s 358 358 ///and target node \c t. 359 359 ///\return the new arc. 360 Arc addArc(const Node& s, const Node& t) { 361 return Parent::addArc(s, t); 360 Arc addArc(const Node& s, const Node& t) { 361 return Parent::addArc(s, t); 362 362 } 363 363 … … 365 365 366 366 /// This function gives back true if the given node is valid, 367 /// ie. it is a real node of the graph. 367 /// ie. it is a real node of the graph. 368 368 /// 369 369 /// \warning A Node pointing to a removed item … … 375 375 376 376 /// This function gives back true if the given arc is valid, 377 /// ie. it is a real arc of the graph. 377 /// ie. it is a real arc of the graph. 378 378 /// 379 379 /// \warning An Arc pointing to a removed item … … 392 392 ///\warning This functionality cannot be used together with the Snapshot 393 393 ///feature. 394 void changeTarget(Arc e, Node n) { 395 Parent::changeTarget(e,n); 394 void changeTarget(Arc e, Node n) { 395 Parent::changeTarget(e,n); 396 396 } 397 397 /// Change the source of \c e to \c n … … 405 405 ///\warning This functionality cannot be used together with the Snapshot 406 406 ///feature. 407 void changeSource(Arc e, Node n) { 407 void changeSource(Arc e, Node n) { 408 408 Parent::changeSource(e,n); 409 409 } … … 457 457 ///\warning This functionality cannot be used together with the Snapshot 458 458 ///feature. 459 void contract(Node a, Node b, bool r = true) 459 void contract(Node a, Node b, bool r = true) 460 460 { 461 461 for(OutArcIt e(*this,b);e!=INVALID;) { 462 463 464 465 466 462 OutArcIt f=e; 463 ++f; 464 if(r && target(e)==a) erase(e); 465 else changeSource(e,a); 466 e=f; 467 467 } 468 468 for(InArcIt e(*this,b);e!=INVALID;) { 469 470 471 472 473 469 InArcIt f=e; 470 ++f; 471 if(r && source(e)==a) erase(e); 472 else changeTarget(e,a); 473 e=f; 474 474 } 475 475 erase(b); … … 486 486 ///\note The <tt>ArcIt</tt>s referencing a moved arc remain 487 487 ///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s may 488 ///be invalidated. 488 ///be invalidated. 489 489 /// 490 490 ///\warning This functionality cannot be used together with the … … 495 495 Node b = addNode(); 496 496 for(OutArcIt e(*this,n);e!=INVALID;) { 497 498 499 500 497 OutArcIt f=e; 498 ++f; 499 changeSource(e,b); 500 e=f; 501 501 } 502 502 if (connect) addArc(n,b); 503 503 return b; 504 504 } 505 505 506 506 ///Split an arc. 507 507 … … 520 520 return b; 521 521 } 522 522 523 523 /// \brief Class to make a snapshot of the digraph and restore 524 524 /// it later. … … 530 530 /// 531 531 /// \warning Arc and node deletions and other modifications (e.g. 532 /// contracting, splitting, reversing arcs or nodes) cannot be 533 /// restored. These events invalidate the snapshot. 532 /// contracting, splitting, reversing arcs or nodes) cannot be 533 /// restored. These events invalidate the snapshot. 534 534 class Snapshot { 535 535 protected: … … 546 546 using NodeNotifier::ObserverBase::detach; 547 547 using NodeNotifier::ObserverBase::attached; 548 548 549 549 protected: 550 550 551 551 virtual void add(const Node& node) { 552 552 snapshot.addNode(node); … … 568 568 Node node; 569 569 std::vector<Node> nodes; 570 for (notifier()->first(node); node != INVALID; 570 for (notifier()->first(node); node != INVALID; 571 571 notifier()->next(node)) { 572 572 nodes.push_back(node); … … 578 578 virtual void clear() { 579 579 Node node; 580 for (notifier()->first(node); node != INVALID; 580 for (notifier()->first(node); node != INVALID; 581 581 notifier()->next(node)) { 582 582 snapshot.eraseNode(node); … … 596 596 using ArcNotifier::ObserverBase::detach; 597 597 using ArcNotifier::ObserverBase::attached; 598 598 599 599 protected: 600 600 … … 618 618 Arc arc; 619 619 std::vector<Arc> arcs; 620 for (notifier()->first(arc); arc != INVALID; 620 for (notifier()->first(arc); arc != INVALID; 621 621 notifier()->next(arc)) { 622 622 arcs.push_back(arc); … … 628 628 virtual void clear() { 629 629 Arc arc; 630 for (notifier()->first(arc); arc != INVALID; 630 for (notifier()->first(arc); arc != INVALID; 631 631 notifier()->next(arc)) { 632 632 snapshot.eraseArc(arc); … … 636 636 Snapshot& snapshot; 637 637 }; 638 638 639 639 ListDigraph *digraph; 640 640 … … 647 647 648 648 void addNode(const Node& node) { 649 added_nodes.push_front(node); 649 added_nodes.push_front(node); 650 650 } 651 651 void eraseNode(const Node& node) { 652 std::list<Node>::iterator it = 652 std::list<Node>::iterator it = 653 653 std::find(added_nodes.begin(), added_nodes.end(), node); 654 654 if (it == added_nodes.end()) { … … 662 662 663 663 void addArc(const Arc& arc) { 664 added_arcs.push_front(arc); 664 added_arcs.push_front(arc); 665 665 } 666 666 void eraseArc(const Arc& arc) { 667 std::list<Arc>::iterator it = 667 std::list<Arc>::iterator it = 668 668 std::find(added_arcs.begin(), added_arcs.end(), arc); 669 669 if (it == added_arcs.end()) { 670 670 clear(); 671 node_observer_proxy.detach(); 671 node_observer_proxy.detach(); 672 672 throw ArcNotifier::ImmediateDetach(); 673 673 } else { 674 674 added_arcs.erase(it); 675 } 675 } 676 676 } 677 677 678 678 void attach(ListDigraph &_digraph) { 679 680 679 digraph = &_digraph; 680 node_observer_proxy.attach(digraph->notifier(Node())); 681 681 arc_observer_proxy.attach(digraph->notifier(Arc())); 682 682 } 683 683 684 684 void detach() { 685 686 685 node_observer_proxy.detach(); 686 arc_observer_proxy.detach(); 687 687 } 688 688 … … 693 693 void clear() { 694 694 added_nodes.clear(); 695 added_arcs.clear(); 695 added_arcs.clear(); 696 696 } 697 697 … … 702 702 /// Default constructor. 703 703 /// To actually make a snapshot you must call save(). 704 Snapshot() 705 : digraph(0), node_observer_proxy(*this), 704 Snapshot() 705 : digraph(0), node_observer_proxy(*this), 706 706 arc_observer_proxy(*this) {} 707 707 708 708 /// \brief Constructor that immediately makes a snapshot. 709 /// 709 /// 710 710 /// This constructor immediately makes a snapshot of the digraph. 711 711 /// \param _digraph The digraph we make a snapshot of. 712 Snapshot(ListDigraph &_digraph) 713 : node_observer_proxy(*this), 712 Snapshot(ListDigraph &_digraph) 713 : node_observer_proxy(*this), 714 714 arc_observer_proxy(*this) { 715 716 } 717 715 attach(_digraph); 716 } 717 718 718 /// \brief Make a snapshot. 719 719 /// … … 730 730 attach(_digraph); 731 731 } 732 732 733 733 /// \brief Undo the changes until the last snapshot. 734 // 734 // 735 735 /// Undo the changes until the last snapshot created by save(). 736 736 void restore() { 737 738 for(std::list<Arc>::iterator it = added_arcs.begin(); 737 detach(); 738 for(std::list<Arc>::iterator it = added_arcs.begin(); 739 739 it != added_arcs.end(); ++it) { 740 741 742 for(std::list<Node>::iterator it = added_nodes.begin(); 740 digraph->erase(*it); 741 } 742 for(std::list<Node>::iterator it = added_nodes.begin(); 743 743 it != added_nodes.end(); ++it) { 744 745 744 digraph->erase(*it); 745 } 746 746 clear(); 747 747 } … … 754 754 } 755 755 }; 756 756 757 757 }; 758 758 … … 767 767 int prev, next; 768 768 }; 769 769 770 770 struct ArcT { 771 771 int target; … … 782 782 783 783 int first_free_arc; 784 784 785 785 public: 786 786 787 787 typedef ListGraphBase Digraph; 788 788 … … 790 790 class Arc; 791 791 class Edge; 792 792 793 793 class Node { 794 794 friend class ListGraphBase; … … 842 842 ListGraphBase() 843 843 : nodes(), first_node(-1), 844 845 846 847 int maxNodeId() const { return nodes.size()-1; } 844 first_free_node(-1), arcs(), first_free_arc(-1) {} 845 846 847 int maxNodeId() const { return nodes.size()-1; } 848 848 int maxEdgeId() const { return arcs.size() / 2 - 1; } 849 849 int maxArcId() const { return arcs.size()-1; } … … 863 863 } 864 864 865 void first(Node& node) const { 865 void first(Node& node) const { 866 866 node.id = first_node; 867 867 } … … 871 871 } 872 872 873 void first(Arc& e) const { 873 void first(Arc& e) const { 874 874 int n = first_node; 875 875 while (n != -1 && nodes[n].first_out == -1) { … … 881 881 void next(Arc& e) const { 882 882 if (arcs[e.id].next_out != -1) { 883 884 } else { 885 883 e.id = arcs[e.id].next_out; 884 } else { 885 int n = nodes[arcs[e.id ^ 1].target].next; 886 886 while(n != -1 && nodes[n].first_out == -1) { 887 887 n = nodes[n].next; 888 888 } 889 890 } 891 } 892 893 void first(Edge& e) const { 889 e.id = (n == -1) ? -1 : nodes[n].first_out; 890 } 891 } 892 893 void first(Edge& e) const { 894 894 int n = first_node; 895 895 while (n != -1) { … … 901 901 e.id /= 2; 902 902 return; 903 } 903 } 904 904 n = nodes[n].next; 905 905 } … … 916 916 e.id /= 2; 917 917 return; 918 } 918 } 919 919 n = nodes[n].next; 920 920 while (n != -1) { … … 926 926 e.id /= 2; 927 927 return; 928 } 928 } 929 929 n = nodes[n].next; 930 930 } … … 968 968 } 969 969 } 970 970 971 971 static int id(Node v) { return v.id; } 972 972 static int id(Arc e) { return e.id; } … … 977 977 static Edge edgeFromId(int id) { return Edge(id);} 978 978 979 bool valid(Node n) const { 980 return n.id >= 0 && n.id < static_cast<int>(nodes.size()) && 981 982 } 983 984 bool valid(Arc a) const { 985 return a.id >= 0 && a.id < static_cast<int>(arcs.size()) && 986 987 } 988 989 bool valid(Edge e) const { 990 return e.id >= 0 && 2 * e.id < static_cast<int>(arcs.size()) && 991 992 } 993 994 Node addNode() { 979 bool valid(Node n) const { 980 return n.id >= 0 && n.id < static_cast<int>(nodes.size()) && 981 nodes[n.id].prev != -2; 982 } 983 984 bool valid(Arc a) const { 985 return a.id >= 0 && a.id < static_cast<int>(arcs.size()) && 986 arcs[a.id].prev_out != -2; 987 } 988 989 bool valid(Edge e) const { 990 return e.id >= 0 && 2 * e.id < static_cast<int>(arcs.size()) && 991 arcs[2 * e.id].prev_out != -2; 992 } 993 994 Node addNode() { 995 995 int n; 996 996 997 997 if(first_free_node==-1) { 998 999 1000 } else { 1001 1002 1003 } 1004 998 n = nodes.size(); 999 nodes.push_back(NodeT()); 1000 } else { 1001 n = first_free_node; 1002 first_free_node = nodes[n].next; 1003 } 1004 1005 1005 nodes[n].next = first_node; 1006 1006 if (first_node != -1) nodes[first_node].prev = n; 1007 1007 first_node = n; 1008 1008 nodes[n].prev = -1; 1009 1009 1010 1010 nodes[n].first_out = -1; 1011 1011 1012 1012 return Node(n); 1013 1013 } 1014 1014 1015 1015 Edge addEdge(Node u, Node v) { 1016 int n; 1016 int n; 1017 1017 1018 1018 if (first_free_arc == -1) { 1019 1020 1021 1022 } else { 1023 1024 1025 } 1026 1019 n = arcs.size(); 1020 arcs.push_back(ArcT()); 1021 arcs.push_back(ArcT()); 1022 } else { 1023 n = first_free_arc; 1024 first_free_arc = arcs[n].next_out; 1025 } 1026 1027 1027 arcs[n].target = u.id; 1028 1028 arcs[n | 1].target = v.id; … … 1030 1030 arcs[n].next_out = nodes[v.id].first_out; 1031 1031 if (nodes[v.id].first_out != -1) { 1032 1033 } 1032 arcs[nodes[v.id].first_out].prev_out = n; 1033 } 1034 1034 arcs[n].prev_out = -1; 1035 1035 nodes[v.id].first_out = n; 1036 1036 1037 1037 arcs[n | 1].next_out = nodes[u.id].first_out; 1038 1038 if (nodes[u.id].first_out != -1) { 1039 1040 } 1041 arcs[n | 1].prev_out = -1; 1039 arcs[nodes[u.id].first_out].prev_out = (n | 1); 1040 } 1041 arcs[n | 1].prev_out = -1; 1042 1042 nodes[u.id].first_out = (n | 1); 1043 1043 1044 1044 return Edge(n / 2); 1045 1045 } 1046 1046 1047 1047 void erase(const Node& node) { 1048 1048 int n = node.id; 1049 1049 1050 1050 if(nodes[n].next != -1) { 1051 1052 } 1053 1051 nodes[nodes[n].next].prev = nodes[n].prev; 1052 } 1053 1054 1054 if(nodes[n].prev != -1) { 1055 1056 } else { 1057 1058 } 1059 1055 nodes[nodes[n].prev].next = nodes[n].next; 1056 } else { 1057 first_node = nodes[n].next; 1058 } 1059 1060 1060 nodes[n].next = first_free_node; 1061 1061 first_free_node = n; 1062 1062 nodes[n].prev = -2; 1063 1063 } 1064 1064 1065 1065 void erase(const Edge& edge) { 1066 1066 int n = edge.id * 2; 1067 1067 1068 1068 if (arcs[n].next_out != -1) { 1069 1070 } 1069 arcs[arcs[n].next_out].prev_out = arcs[n].prev_out; 1070 } 1071 1071 1072 1072 if (arcs[n].prev_out != -1) { 1073 1074 } else { 1075 1073 arcs[arcs[n].prev_out].next_out = arcs[n].next_out; 1074 } else { 1075 nodes[arcs[n | 1].target].first_out = arcs[n].next_out; 1076 1076 } 1077 1077 1078 1078 if (arcs[n | 1].next_out != -1) { 1079 1080 } 1079 arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out; 1080 } 1081 1081 1082 1082 if (arcs[n | 1].prev_out != -1) { 1083 1084 } else { 1085 1086 } 1087 1083 arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out; 1084 } else { 1085 nodes[arcs[n].target].first_out = arcs[n | 1].next_out; 1086 } 1087 1088 1088 arcs[n].next_out = first_free_arc; 1089 first_free_arc = n; 1089 first_free_arc = n; 1090 1090 arcs[n].prev_out = -2; 1091 1091 arcs[n | 1].prev_out = -2; … … 1103 1103 void changeTarget(Edge e, Node n) { 1104 1104 if(arcs[2 * e.id].next_out != -1) { 1105 1105 arcs[arcs[2 * e.id].next_out].prev_out = arcs[2 * e.id].prev_out; 1106 1106 } 1107 1107 if(arcs[2 * e.id].prev_out != -1) { 1108 arcs[arcs[2 * e.id].prev_out].next_out = 1108 arcs[arcs[2 * e.id].prev_out].next_out = 1109 1109 arcs[2 * e.id].next_out; 1110 1110 } else { 1111 nodes[arcs[(2 * e.id) | 1].target].first_out = 1111 nodes[arcs[(2 * e.id) | 1].target].first_out = 1112 1112 arcs[2 * e.id].next_out; 1113 1113 } 1114 1114 1115 1115 if (nodes[n.id].first_out != -1) { 1116 1116 arcs[nodes[n.id].first_out].prev_out = 2 * e.id; 1117 1117 } 1118 1118 arcs[(2 * e.id) | 1].target = n.id; … … 1124 1124 void changeSource(Edge e, Node n) { 1125 1125 if(arcs[(2 * e.id) | 1].next_out != -1) { 1126 arcs[arcs[(2 * e.id) | 1].next_out].prev_out = 1126 arcs[arcs[(2 * e.id) | 1].next_out].prev_out = 1127 1127 arcs[(2 * e.id) | 1].prev_out; 1128 1128 } 1129 1129 if(arcs[(2 * e.id) | 1].prev_out != -1) { 1130 arcs[arcs[(2 * e.id) | 1].prev_out].next_out = 1130 arcs[arcs[(2 * e.id) | 1].prev_out].next_out = 1131 1131 arcs[(2 * e.id) | 1].next_out; 1132 1132 } else { 1133 nodes[arcs[2 * e.id].target].first_out = 1133 nodes[arcs[2 * e.id].target].first_out = 1134 1134 arcs[(2 * e.id) | 1].next_out; 1135 1135 } 1136 1136 1137 1137 if (nodes[n.id].first_out != -1) { 1138 1138 arcs[nodes[n.id].first_out].prev_out = ((2 * e.id) | 1); 1139 1139 } 1140 1140 arcs[2 * e.id].target = n.id; … … 1154 1154 ///A general undirected graph structure. 1155 1155 1156 ///\ref ListGraph is a simple and fast <em>undirected graph</em> 1157 ///implementation based on static linked lists that are stored in 1158 ///\c std::vector structures. 1156 ///\ref ListGraph is a simple and fast <em>undirected graph</em> 1157 ///implementation based on static linked lists that are stored in 1158 ///\c std::vector structures. 1159 1159 /// 1160 1160 ///It conforms to the \ref concepts::Graph "Graph concept" and it … … 1183 1183 public: 1184 1184 /// Constructor 1185 1185 1186 1186 /// Constructor. 1187 1187 /// … … 1203 1203 /// and target node \c t. 1204 1204 /// \return the new edge. 1205 Edge addEdge(const Node& s, const Node& t) { 1206 return Parent::addEdge(s, t); 1205 Edge addEdge(const Node& s, const Node& t) { 1206 return Parent::addEdge(s, t); 1207 1207 } 1208 1208 /// Node validity check 1209 1209 1210 1210 /// This function gives back true if the given node is valid, 1211 /// ie. it is a real node of the graph. 1211 /// ie. it is a real node of the graph. 1212 1212 /// 1213 1213 /// \warning A Node pointing to a removed item … … 1218 1218 1219 1219 /// This function gives back true if the given arc is valid, 1220 /// ie. it is a real arc of the graph. 1220 /// ie. it is a real arc of the graph. 1221 1221 /// 1222 1222 /// \warning An Arc pointing to a removed item … … 1227 1227 1228 1228 /// This function gives back true if the given edge is valid, 1229 /// ie. it is a real arc of the graph. 1229 /// ie. it is a real arc of the graph. 1230 1230 /// 1231 1231 /// \warning A Edge pointing to a removed item … … 1243 1243 ///\warning This functionality cannot be used together with the 1244 1244 ///Snapshot feature. 1245 void changeSource(Edge e, Node n) { 1246 Parent::changeSource(e,n); 1247 } 1245 void changeSource(Edge e, Node n) { 1246 Parent::changeSource(e,n); 1247 } 1248 1248 /// \brief Change the target of \c e to \c n 1249 1249 /// … … 1255 1255 ///\warning This functionality cannot be used together with the 1256 1256 ///Snapshot feature. 1257 void changeTarget(Edge e, Node n) { 1258 Parent::changeTarget(e,n); 1257 void changeTarget(Edge e, Node n) { 1258 Parent::changeTarget(e,n); 1259 1259 } 1260 1260 /// \brief Change the source of \c e to \c n 1261 1261 /// 1262 /// This function changes the source of \c e to \c n. 1262 /// This function changes the source of \c e to \c n. 1263 1263 /// It also changes the proper node of the represented edge. 1264 1264 /// … … 1269 1269 ///\warning This functionality cannot be used together with the 1270 1270 ///Snapshot feature. 1271 void changeSource(Arc e, Node n) { 1271 void changeSource(Arc e, Node n) { 1272 1272 if (Parent::direction(e)) { 1273 1273 Parent::changeSource(e,n); 1274 1274 } else { 1275 1275 Parent::changeTarget(e,n); 1276 } 1276 } 1277 1277 } 1278 1278 /// \brief Change the target of \c e to \c n 1279 1279 /// 1280 /// This function changes the target of \c e to \c n. 1280 /// This function changes the target of \c e to \c n. 1281 1281 /// It also changes the proper node of the represented edge. 1282 1282 /// … … 1287 1287 ///\warning This functionality cannot be used together with the 1288 1288 ///Snapshot feature. 1289 void changeTarget(Arc e, Node n) { 1289 void changeTarget(Arc e, Node n) { 1290 1290 if (Parent::direction(e)) { 1291 1291 Parent::changeTarget(e,n); 1292 1292 } else { 1293 1293 Parent::changeSource(e,n); 1294 } 1294 } 1295 1295 } 1296 1296 /// \brief Contract two nodes. … … 1309 1309 void contract(Node a, Node b, bool r = true) { 1310 1310 for(IncEdgeIt e(*this, b); e!=INVALID;) { 1311 1312 1313 1314 1315 1316 1317 1318 1319 1311 IncEdgeIt f = e; ++f; 1312 if (r && runningNode(e) == a) { 1313 erase(e); 1314 } else if (source(e) == b) { 1315 changeSource(e, a); 1316 } else { 1317 changeTarget(e, a); 1318 } 1319 e = f; 1320 1320 } 1321 1321 erase(b); … … 1332 1332 /// 1333 1333 /// \warning Edge and node deletions and other modifications 1334 /// (e.g. changing nodes of edges, contracting nodes) cannot be 1334 /// (e.g. changing nodes of edges, contracting nodes) cannot be 1335 1335 /// restored. These events invalidate the snapshot. 1336 1336 class Snapshot { … … 1348 1348 using NodeNotifier::ObserverBase::detach; 1349 1349 using NodeNotifier::ObserverBase::attached; 1350 1350 1351 1351 protected: 1352 1352 1353 1353 virtual void add(const Node& node) { 1354 1354 snapshot.addNode(node); … … 1370 1370 Node node; 1371 1371 std::vector<Node> nodes; 1372 for (notifier()->first(node); node != INVALID; 1372 for (notifier()->first(node); node != INVALID; 1373 1373 notifier()->next(node)) { 1374 1374 nodes.push_back(node); … … 1380 1380 virtual void clear() { 1381 1381 Node node; 1382 for (notifier()->first(node); node != INVALID; 1382 for (notifier()->first(node); node != INVALID; 1383 1383 notifier()->next(node)) { 1384 1384 snapshot.eraseNode(node); … … 1398 1398 using EdgeNotifier::ObserverBase::detach; 1399 1399 using EdgeNotifier::ObserverBase::attached; 1400 1400 1401 1401 protected: 1402 1402 … … 1420 1420 Edge edge; 1421 1421 std::vector<Edge> edges; 1422 for (notifier()->first(edge); edge != INVALID; 1422 for (notifier()->first(edge); edge != INVALID; 1423 1423 notifier()->next(edge)) { 1424 1424 edges.push_back(edge); … … 1430 1430 virtual void clear() { 1431 1431 Edge edge; 1432 for (notifier()->first(edge); edge != INVALID; 1432 for (notifier()->first(edge); edge != INVALID; 1433 1433 notifier()->next(edge)) { 1434 1434 snapshot.eraseEdge(edge); … … 1449 1449 1450 1450 void addNode(const Node& node) { 1451 added_nodes.push_front(node); 1451 added_nodes.push_front(node); 1452 1452 } 1453 1453 void eraseNode(const Node& node) { 1454 std::list<Node>::iterator it = 1454 std::list<Node>::iterator it = 1455 1455 std::find(added_nodes.begin(), added_nodes.end(), node); 1456 1456 if (it == added_nodes.end()) { … … 1464 1464 1465 1465 void addEdge(const Edge& edge) { 1466 added_edges.push_front(edge); 1466 added_edges.push_front(edge); 1467 1467 } 1468 1468 void eraseEdge(const Edge& edge) { 1469 std::list<Edge>::iterator it = 1469 std::list<Edge>::iterator it = 1470 1470 std::find(added_edges.begin(), added_edges.end(), edge); 1471 1471 if (it == added_edges.end()) { … … 1479 1479 1480 1480 void attach(ListGraph &_graph) { 1481 1482 1481 graph = &_graph; 1482 node_observer_proxy.attach(graph->notifier(Node())); 1483 1483 edge_observer_proxy.attach(graph->notifier(Edge())); 1484 1484 } 1485 1485 1486 1486 void detach() { 1487 1488 1487 node_observer_proxy.detach(); 1488 edge_observer_proxy.detach(); 1489 1489 } 1490 1490 … … 1495 1495 void clear() { 1496 1496 added_nodes.clear(); 1497 added_edges.clear(); 1497 added_edges.clear(); 1498 1498 } 1499 1499 … … 1504 1504 /// Default constructor. 1505 1505 /// To actually make a snapshot you must call save(). 1506 Snapshot() 1507 : graph(0), node_observer_proxy(*this), 1506 Snapshot() 1507 : graph(0), node_observer_proxy(*this), 1508 1508 edge_observer_proxy(*this) {} 1509 1509 1510 1510 /// \brief Constructor that immediately makes a snapshot. 1511 /// 1511 /// 1512 1512 /// This constructor immediately makes a snapshot of the graph. 1513 1513 /// \param _graph The graph we make a snapshot of. 1514 Snapshot(ListGraph &_graph) 1515 : node_observer_proxy(*this), 1514 Snapshot(ListGraph &_graph) 1515 : node_observer_proxy(*this), 1516 1516 edge_observer_proxy(*this) { 1517 1518 } 1519 1517 attach(_graph); 1518 } 1519 1520 1520 /// \brief Make a snapshot. 1521 1521 /// … … 1532 1532 attach(_graph); 1533 1533 } 1534 1534 1535 1535 /// \brief Undo the changes until the last snapshot. 1536 // 1536 // 1537 1537 /// Undo the changes until the last snapshot created by save(). 1538 1538 void restore() { 1539 1540 for(std::list<Edge>::iterator it = added_edges.begin(); 1539 detach(); 1540 for(std::list<Edge>::iterator it = added_edges.begin(); 1541 1541 it != added_edges.end(); ++it) { 1542 1543 1544 for(std::list<Node>::iterator it = added_nodes.begin(); 1542 graph->erase(*it); 1543 } 1544 for(std::list<Node>::iterator it = added_nodes.begin(); 1545 1545 it != added_nodes.end(); ++it) { 1546 1547 1546 graph->erase(*it); 1547 } 1548 1548 clear(); 1549 1549 } … … 1557 1557 }; 1558 1558 }; 1559 1560 /// @} 1559 1560 /// @} 1561 1561 } //namespace lemon 1562 1562 1563 1563 1564 1564 #endif -
lemon/maps.h
r167 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 405 405 typename Map::iterator it = _map.lower_bound(k); 406 406 if (it != _map.end() && !_map.key_comp()(k, it->first)) 407 407 return it->second; 408 408 else 409 409 return _map.insert(it, std::make_pair(k, _value))->second; 410 410 } 411 411 … … 414 414 typename Map::const_iterator it = _map.find(k); 415 415 if (it != _map.end()) 416 416 return it->second; 417 417 else 418 418 return _value; 419 419 } 420 420 … … 423 423 typename Map::iterator it = _map.lower_bound(k); 424 424 if (it != _map.end() && !_map.key_comp()(k, it->first)) 425 425 it->second = v; 426 426 else 427 427 _map.insert(it, std::make_pair(k, v)); 428 428 } 429 429 … … 545 545 /// \todo Check the requirements. 546 546 template<typename M1, typename M2, typename F, 547 547 typename V = typename F::result_type> 548 548 class CombineMap : public MapBase<typename M1::Key, V> { 549 549 const M1 &_m1; … … 616 616 /// \sa MapToFunctor 617 617 template<typename F, 618 619 618 typename K = typename F::argument_type, 619 typename V = typename F::result_type> 620 620 class FunctorToMap : public MapBase<K, V> { 621 621 F _f; … … 1318 1318 1319 1319 /// @} 1320 1320 1321 1321 // Logical maps and map adaptors: 1322 1322 … … 1716 1716 #else 1717 1717 template <typename It, 1718 1718 typename Ke=typename _maps_bits::IteratorTraits<It>::Value> 1719 1719 #endif 1720 1720 class LoggerBoolMap { … … 1742 1742 void set(const Key& key, Value value) { 1743 1743 if (value) { 1744 1744 *_end++ = key; 1745 1745 } 1746 1746 } … … 1750 1750 Iterator _end; 1751 1751 }; 1752 1752 1753 1753 /// Returns a \ref LoggerBoolMap class 1754 1754 -
lemon/math.h
r68 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 34 34 /// \addtogroup misc 35 35 /// @{ 36 36 37 37 /// The Euler constant 38 38 const long double E = 2.7182818284590452353602874713526625L; … … 55 55 /// 1/sqrt(2) 56 56 const long double SQRT1_2 = 0.7071067811865475244008443621048490L; 57 57 58 58 59 59 /// @} -
lemon/path.h
r157 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 94 94 ArcIt(Invalid) : path(0), idx(-1) {} 95 95 /// \brief Initializate the iterator to the first arc of path 96 ArcIt(const Path &_path) 96 ArcIt(const Path &_path) 97 97 : path(&_path), idx(_path.empty() ? -1 : 0) {} 98 98 99 99 private: 100 100 101 ArcIt(const Path &_path, int _idx) 101 ArcIt(const Path &_path, int _idx) 102 102 : path(&_path), idx(_idx) {} 103 103 … … 110 110 111 111 /// \brief Next arc 112 ArcIt& operator++() { 112 ArcIt& operator++() { 113 113 ++idx; 114 if (idx >= path->length()) idx = -1; 115 return *this; 114 if (idx >= path->length()) idx = -1; 115 return *this; 116 116 } 117 117 … … 285 285 ArcIt(Invalid) : path(0), idx(-1) {} 286 286 /// \brief Initializate the constructor to the first arc of path 287 ArcIt(const SimplePath &_path) 287 ArcIt(const SimplePath &_path) 288 288 : path(&_path), idx(_path.empty() ? -1 : 0) {} 289 289 … … 291 291 292 292 /// Constructor with starting point 293 ArcIt(const SimplePath &_path, int _idx) 293 ArcIt(const SimplePath &_path, int _idx) 294 294 : idx(_idx), path(&_path) {} 295 295 … … 302 302 303 303 /// Next arc 304 ArcIt& operator++() { 304 ArcIt& operator++() { 305 305 ++idx; 306 if (idx >= path->length()) idx = -1; 307 return *this; 306 if (idx >= path->length()) idx = -1; 307 return *this; 308 308 } 309 309 … … 414 414 protected: 415 415 416 // the std::list<> is incompatible 416 // the std::list<> is incompatible 417 417 // hard to create invalid iterator 418 418 struct Node { … … 426 426 427 427 public: 428 428 429 429 /// \brief Default constructor 430 430 /// … … 471 471 ArcIt(Invalid) : path(0), node(0) {} 472 472 /// \brief Initializate the constructor to the first arc of path 473 ArcIt(const ListPath &_path) 473 ArcIt(const ListPath &_path) 474 474 : path(&_path), node(_path.first) {} 475 475 476 476 protected: 477 477 478 ArcIt(const ListPath &_path, Node *_node) 478 ArcIt(const ListPath &_path, Node *_node) 479 479 : path(&_path), node(_node) {} 480 480 … … 488 488 489 489 /// Next arc 490 ArcIt& operator++() { 490 ArcIt& operator++() { 491 491 node = node->next; 492 return *this; 492 return *this; 493 493 } 494 494 … … 758 758 /// Default constructor 759 759 StaticPath() : len(0), arcs(0) {} 760 760 761 761 /// \brief Template copy constructor 762 762 /// … … 797 797 ArcIt(Invalid) : path(0), idx(-1) {} 798 798 /// Initializate the constructor to the first arc of path 799 ArcIt(const StaticPath &_path) 799 ArcIt(const StaticPath &_path) 800 800 : path(&_path), idx(_path.empty() ? -1 : 0) {} 801 801 … … 803 803 804 804 /// Constructor with starting point 805 ArcIt(const StaticPath &_path, int _idx) 805 ArcIt(const StaticPath &_path, int _idx) 806 806 : idx(_idx), path(&_path) {} 807 807 … … 814 814 815 815 /// Next arc 816 ArcIt& operator++() { 816 ArcIt& operator++() { 817 817 ++idx; 818 if (idx >= path->length()) idx = -1; 819 return *this; 818 if (idx >= path->length()) idx = -1; 819 return *this; 820 820 } 821 821 … … 910 910 template <typename Path> 911 911 struct RevPathTagIndicator< 912 Path, 912 Path, 913 913 typename enable_if<typename Path::RevPathTag, void>::type 914 914 > { … … 923 923 template <typename Path> 924 924 struct BuildTagIndicator< 925 Path, 925 Path, 926 926 typename enable_if<typename Path::BuildTag, void>::type 927 927 > { … … 930 930 931 931 template <typename Target, typename Source, 932 bool buildEnable = BuildTagIndicator<Target>::value, 933 932 bool buildEnable = BuildTagIndicator<Target>::value, 933 bool revEnable = RevPathTagIndicator<Source>::value> 934 934 struct PathCopySelector { 935 935 static void copy(Target& target, const Source& source) { … … 982 982 /// 983 983 /// This function checks that the target of each arc is the same 984 /// as the source of the next one. 985 /// 984 /// as the source of the next one. 985 /// 986 986 template <typename Digraph, typename Path> 987 987 bool checkPath(const Digraph& digraph, const Path& path) { … … 1035 1035 typedef typename Path::Digraph Digraph; 1036 1036 typedef typename Digraph::Node Node; 1037 1037 1038 1038 /// Default constructor 1039 1039 PathNodeIt() {} 1040 1040 /// Invalid constructor 1041 PathNodeIt(Invalid) 1041 PathNodeIt(Invalid) 1042 1042 : _digraph(0), _it(INVALID), _nd(INVALID) {} 1043 1043 /// Constructor 1044 PathNodeIt(const Digraph& digraph, const Path& path) 1044 PathNodeIt(const Digraph& digraph, const Path& path) 1045 1045 : _digraph(&digraph), _it(path) { 1046 1046 _nd = (_it != INVALID ? _digraph->source(_it) : INVALID); 1047 1047 } 1048 1048 /// Constructor 1049 PathNodeIt(const Digraph& digraph, const Path& path, const Node& src) 1049 PathNodeIt(const Digraph& digraph, const Path& path, const Node& src) 1050 1050 : _digraph(&digraph), _it(path), _nd(src) {} 1051 1051 … … 1059 1059 if (_it == INVALID) _nd = INVALID; 1060 1060 else { 1061 1062 1061 _nd = _digraph->target(_it); 1062 ++_it; 1063 1063 } 1064 1064 return *this; … … 1066 1066 1067 1067 /// Comparison operator 1068 bool operator==(const PathNodeIt& n) const { 1069 return _it == n._it && _nd == n._nd; 1068 bool operator==(const PathNodeIt& n) const { 1069 return _it == n._it && _nd == n._nd; 1070 1070 } 1071 1071 /// Comparison operator 1072 bool operator!=(const PathNodeIt& n) const { 1073 return _it != n._it || _nd != n._nd; 1072 bool operator!=(const PathNodeIt& n) const { 1073 return _it != n._it || _nd != n._nd; 1074 1074 } 1075 1075 /// Comparison operator 1076 bool operator<(const PathNodeIt& n) const { 1076 bool operator<(const PathNodeIt& n) const { 1077 1077 return (_it < n._it && _nd != INVALID); 1078 1078 } 1079 1079 1080 1080 }; 1081 1081 1082 1082 ///@} 1083 1083 -
lemon/random.cc
r39 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
lemon/random.h
r178 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 22 22 * 23 23 * See the appropriate copyright notice below. 24 * 24 * 25 25 * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, 26 * All rights reserved. 26 * All rights reserved. 27 27 * 28 28 * Redistribution and use in source and binary forms, with or without … … 37 37 * documentation and/or other materials provided with the distribution. 38 38 * 39 * 3. The names of its contributors may not be used to endorse or promote 40 * products derived from this software without specific prior written 39 * 3. The names of its contributors may not be used to endorse or promote 40 * products derived from this software without specific prior written 41 41 * permission. 42 42 * … … 88 88 89 89 namespace _random_bits { 90 90 91 91 template <typename _Word, int _bits = std::numeric_limits<_Word>::digits> 92 92 struct RandomTraits {}; … … 100 100 static const int length = 624; 101 101 static const int shift = 397; 102 102 103 103 static const Word mul = 0x6c078965u; 104 104 static const Word arrayInit = 0x012BD6AAu; … … 168 168 0x12345u, 0x23456u, 0x34567u, 0x45678u 169 169 }; 170 170 171 171 initState(seedArray, seedArray + 4); 172 172 } … … 176 176 static const Word mul = RandomTraits<Word>::mul; 177 177 178 current = state; 178 current = state; 179 179 180 180 Word *curr = state + length - 1; … … 202 202 num = length > end - begin ? length : end - begin; 203 203 while (num--) { 204 curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 204 curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 205 205 + *it + cnt; 206 206 ++it; ++cnt; … … 224 224 } 225 225 } 226 226 227 227 state[length - 1] = Word(1) << (bits - 1); 228 228 } 229 229 230 230 void copyState(const RandomCore& other) { 231 231 std::copy(other.state, other.state + length, state); … … 242 242 private: 243 243 244 244 245 245 void fillState() { 246 246 static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask }; … … 248 248 static const Word hiMask = RandomTraits<Word>::hiMask; 249 249 250 current = state + length; 250 current = state + length; 251 251 252 252 register Word *curr = state + length - 1; 253 253 register long num; 254 254 255 255 num = length - shift; 256 256 while (num--) { … … 270 270 } 271 271 272 272 273 273 Word *current; 274 274 Word state[length]; 275 276 }; 277 278 279 template <typename Result, 275 276 }; 277 278 279 template <typename Result, 280 280 int shift = (std::numeric_limits<Result>::digits + 1) / 2> 281 281 struct Masker { … … 285 285 } 286 286 }; 287 287 288 288 template <typename Result> 289 289 struct Masker<Result, 1> { … … 293 293 }; 294 294 295 template <typename Result, typename Word, 296 int rest = std::numeric_limits<Result>::digits, int shift = 0, 295 template <typename Result, typename Word, 296 int rest = std::numeric_limits<Result>::digits, int shift = 0, 297 297 bool last = rest <= std::numeric_limits<Word>::digits> 298 298 struct IntConversion { 299 299 static const int bits = std::numeric_limits<Word>::digits; 300 300 301 301 static Result convert(RandomCore<Word>& rnd) { 302 302 return static_cast<Result>(rnd() >> (bits - rest)) << shift; 303 303 } 304 305 }; 306 307 template <typename Result, typename Word, int rest, int shift> 304 305 }; 306 307 template <typename Result, typename Word, int rest, int shift> 308 308 struct IntConversion<Result, Word, rest, shift, false> { 309 309 static const int bits = std::numeric_limits<Word>::digits; 310 310 311 311 static Result convert(RandomCore<Word>& rnd) { 312 return (static_cast<Result>(rnd()) << shift) | 312 return (static_cast<Result>(rnd()) << shift) | 313 313 IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd); 314 314 } … … 317 317 318 318 template <typename Result, typename Word, 319 bool one_word = (std::numeric_limits<Word>::digits < 320 319 bool one_word = (std::numeric_limits<Word>::digits < 320 std::numeric_limits<Result>::digits) > 321 321 struct Mapping { 322 322 static Result map(RandomCore<Word>& rnd, const Result& bound) { … … 325 325 Result num; 326 326 do { 327 num = IntConversion<Result, Word>::convert(rnd) & mask; 327 num = IntConversion<Result, Word>::convert(rnd) & mask; 328 328 } while (num > max); 329 329 return num; … … 351 351 res *= res; 352 352 if ((exp & 1) == 1) res *= static_cast<Result>(2.0); 353 return res; 353 return res; 354 354 } 355 355 }; … … 361 361 res *= res; 362 362 if ((exp & 1) == 1) res *= static_cast<Result>(0.5); 363 return res; 363 return res; 364 364 } 365 365 }; … … 368 368 struct ShiftMultiplier<Result, 0, true> { 369 369 static const Result multiplier() { 370 return static_cast<Result>(1.0); 370 return static_cast<Result>(1.0); 371 371 } 372 372 }; … … 375 375 struct ShiftMultiplier<Result, -20, true> { 376 376 static const Result multiplier() { 377 return static_cast<Result>(1.0/1048576.0); 378 } 379 }; 380 377 return static_cast<Result>(1.0/1048576.0); 378 } 379 }; 380 381 381 template <typename Result> 382 382 struct ShiftMultiplier<Result, -32, true> { 383 383 static const Result multiplier() { 384 return static_cast<Result>(1.0/424967296.0); 384 return static_cast<Result>(1.0/424967296.0); 385 385 } 386 386 }; … … 389 389 struct ShiftMultiplier<Result, -53, true> { 390 390 static const Result multiplier() { 391 return static_cast<Result>(1.0/9007199254740992.0); 391 return static_cast<Result>(1.0/9007199254740992.0); 392 392 } 393 393 }; … … 396 396 struct ShiftMultiplier<Result, -64, true> { 397 397 static const Result multiplier() { 398 return static_cast<Result>(1.0/18446744073709551616.0); 398 return static_cast<Result>(1.0/18446744073709551616.0); 399 399 } 400 400 }; … … 408 408 409 409 template <typename Result, typename Word, 410 int rest = std::numeric_limits<Result>::digits, int shift = 0, 410 int rest = std::numeric_limits<Result>::digits, int shift = 0, 411 411 bool last = rest <= std::numeric_limits<Word>::digits> 412 struct RealConversion{ 412 struct RealConversion{ 413 413 static const int bits = std::numeric_limits<Word>::digits; 414 414 … … 420 420 421 421 template <typename Result, typename Word, int rest, int shift> 422 struct RealConversion<Result, Word, rest, shift, false> { 422 struct RealConversion<Result, Word, rest, shift, false> { 423 423 static const int bits = std::numeric_limits<Word>::digits; 424 424 … … 459 459 Word buffer; 460 460 int num; 461 461 462 462 BoolProducer() : num(0) {} 463 463 … … 530 530 // Architecture word 531 531 typedef unsigned long Word; 532 532 533 533 _random_bits::RandomCore<Word> core; 534 534 _random_bits::BoolProducer<Word> bool_producer; 535 535 536 536 537 537 public: … … 555 555 /// to the architecture word type. 556 556 template <typename Number> 557 Random(Number seed) { 557 Random(Number seed) { 558 558 _random_bits::Initializer<Number, Word>::init(core, seed); 559 559 } … … 565 565 /// architecture word type. 566 566 template <typename Iterator> 567 Random(Iterator begin, Iterator end) { 567 Random(Iterator begin, Iterator end) { 568 568 typedef typename std::iterator_traits<Iterator>::value_type Number; 569 569 _random_bits::Initializer<Number, Word>::init(core, begin, end); … … 598 598 /// converted to the architecture word type. 599 599 template <typename Number> 600 void seed(Number seed) { 600 void seed(Number seed) { 601 601 _random_bits::Initializer<Number, Word>::init(core, seed); 602 602 } … … 608 608 /// architecture word type. 609 609 template <typename Iterator> 610 void seed(Iterator begin, Iterator end) { 610 void seed(Iterator begin, Iterator end) { 611 611 typedef typename std::iterator_traits<Iterator>::value_type Number; 612 612 _random_bits::Initializer<Number, Word>::init(core, begin, end); … … 626 626 return false; 627 627 } 628 628 629 629 /// \brief Seeding from file 630 630 /// … … 641 641 /// \return True when the seeding successes. 642 642 #ifndef WIN32 643 bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0) 643 bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0) 644 644 #else 645 bool seedFromFile(const std::string& file = "", int offset = 0) 645 bool seedFromFile(const std::string& file = "", int offset = 0) 646 646 #endif 647 647 { … … 661 661 /// random sequence. 662 662 /// \return Currently always true. 663 bool seedFromTime() { 663 bool seedFromTime() { 664 664 #ifndef WIN32 665 665 timeval tv; … … 697 697 /// It returns a random real number from the range [0, b). 698 698 template <typename Number> 699 Number real(Number b) { 700 return real<Number>() * b; 699 Number real(Number b) { 700 return real<Number>() * b; 701 701 } 702 702 … … 705 705 /// It returns a random real number from the range [a, b). 706 706 template <typename Number> 707 Number real(Number a, Number b) { 708 return real<Number>() * (b - a) + a; 707 Number real(Number a, Number b) { 708 return real<Number>() * (b - a) + a; 709 709 } 710 710 … … 726 726 /// It returns a random real number from the range [0, b). 727 727 template <typename Number> 728 Number operator()(Number b) { 729 return real<Number>() * b; 728 Number operator()(Number b) { 729 return real<Number>() * b; 730 730 } 731 731 … … 734 734 /// It returns a random real number from the range [a, b). 735 735 template <typename Number> 736 Number operator()(Number a, Number b) { 737 return real<Number>() * (b - a) + a; 736 Number operator()(Number a, Number b) { 737 return real<Number>() * (b - a) + a; 738 738 } 739 739 … … 785 785 template <typename Number> 786 786 Number integer() { 787 static const int nb = std::numeric_limits<Number>::digits + 787 static const int nb = std::numeric_limits<Number>::digits + 788 788 (std::numeric_limits<Number>::is_signed ? 1 : 0); 789 789 return _random_bits::IntConversion<Number, Word, nb>::convert(core); … … 793 793 return integer<int>(); 794 794 } 795 795 796 796 /// \brief Returns a random bool 797 797 /// … … 807 807 ///\name Non-uniform distributions 808 808 /// 809 809 810 810 ///@{ 811 811 812 812 /// \brief Returns a random bool 813 813 /// … … 823 823 /// transformation is used to generate a random normal distribution. 824 824 /// \todo Consider using the "ziggurat" method instead. 825 double gauss() 825 double gauss() 826 826 { 827 827 double V1,V2,S; 828 828 do { 829 830 831 829 V1=2*real<double>()-1; 830 V2=2*real<double>()-1; 831 S=V1*V1+V2*V2; 832 832 } while(S>=1); 833 833 return std::sqrt(-2*std::log(S)/S)*V1; … … 855 855 856 856 /// This function generates a gamma distribution random number. 857 /// 857 /// 858 858 ///\param k shape parameter (<tt>k>0</tt> integer) 859 double gamma(int k) 859 double gamma(int k) 860 860 { 861 861 double s = 0; … … 863 863 return s; 864 864 } 865 865 866 866 /// Gamma distribution with given shape and scale parameter 867 867 868 868 /// This function generates a gamma distribution random number. 869 /// 869 /// 870 870 ///\param k shape parameter (<tt>k>0</tt>) 871 871 ///\param theta scale parameter … … 877 877 const double v0=E/(E-delta); 878 878 do { 879 880 881 882 if(V2<=v0) 883 884 885 886 887 else 888 889 890 891 879 double V0=1.0-real<double>(); 880 double V1=1.0-real<double>(); 881 double V2=1.0-real<double>(); 882 if(V2<=v0) 883 { 884 xi=std::pow(V1,1.0/delta); 885 nu=V0*std::pow(xi,delta-1.0); 886 } 887 else 888 { 889 xi=1.0-std::log(V1); 890 nu=V0*std::exp(-xi); 891 } 892 892 } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi)); 893 893 return theta*(xi+gamma(int(std::floor(k)))); 894 894 } 895 895 896 896 /// Weibull distribution 897 897 898 898 /// This function generates a Weibull distribution random number. 899 /// 899 /// 900 900 ///\param k shape parameter (<tt>k>0</tt>) 901 901 ///\param lambda scale parameter (<tt>lambda>0</tt>) … … 904 904 { 905 905 return lambda*pow(-std::log(1.0-real<double>()),1.0/k); 906 } 907 906 } 907 908 908 /// Pareto distribution 909 909 910 910 /// This function generates a Pareto distribution random number. 911 /// 911 /// 912 912 ///\param k shape parameter (<tt>k>0</tt>) 913 913 ///\param x_min location parameter (<tt>x_min>0</tt>) … … 916 916 { 917 917 return exponential(gamma(k,1.0/x_min))+x_min; 918 } 919 918 } 919 920 920 /// Poisson distribution 921 921 922 922 /// This function generates a Poisson distribution random number with 923 923 /// parameter \c lambda. 924 /// 924 /// 925 925 /// The probability mass function of this distribusion is 926 926 /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f] … … 928 928 /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the 929 929 /// return value. 930 930 931 931 int poisson(double lambda) 932 932 { … … 935 935 double p = 1.0; 936 936 do { 937 938 937 k++; 938 p*=real<double>(); 939 939 } while (p>=l); 940 940 return k-1; 941 } 942 941 } 942 943 943 ///@} 944 944 945 945 ///\name Two dimensional distributions 946 946 /// 947 947 948 948 ///@{ 949 949 950 950 /// Uniform distribution on the full unit circle 951 951 952 952 /// Uniform distribution on the full unit circle. 953 953 /// 954 dim2::Point<double> disc() 954 dim2::Point<double> disc() 955 955 { 956 956 double V1,V2; 957 957 do { 958 959 960 958 V1=2*real<double>()-1; 959 V2=2*real<double>()-1; 960 961 961 } while(V1*V1+V2*V2>=1); 962 962 return dim2::Point<double>(V1,V2); … … 974 974 double V1,V2,S; 975 975 do { 976 977 978 976 V1=2*real<double>()-1; 977 V2=2*real<double>()-1; 978 S=V1*V1+V2*V2; 979 979 } while(S>=1); 980 980 double W=std::sqrt(-2*std::log(S)/S); … … 985 985 /// This function provides a turning symmetric two-dimensional distribution. 986 986 /// The x-coordinate is of conditionally exponential distribution 987 /// with the condition that x is positive and y=0. If x is negative and 987 /// with the condition that x is positive and y=0. If x is negative and 988 988 /// y=0 then, -x is of exponential distribution. The same is true for the 989 989 /// y-coordinate. 990 dim2::Point<double> exponential2() 990 dim2::Point<double> exponential2() 991 991 { 992 992 double V1,V2,S; 993 993 do { 994 995 996 994 V1=2*real<double>()-1; 995 V2=2*real<double>()-1; 996 S=V1*V1+V2*V2; 997 997 } while(S>=1); 998 998 double W=-std::log(S)/S; … … 1000 1000 } 1001 1001 1002 ///@} 1002 ///@} 1003 1003 }; 1004 1004 -
lemon/smart_graph.h
r157 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 46 46 protected: 47 47 48 struct NodeT 48 struct NodeT 49 49 { 50 int first_in, first_out; 50 int first_in, first_out; 51 51 NodeT() {} 52 52 }; 53 struct ArcT 53 struct ArcT 54 54 { 55 int target, source, next_in, next_out; 56 ArcT() {} 55 int target, source, next_in, next_out; 56 ArcT() {} 57 57 }; 58 58 59 59 std::vector<NodeT> nodes; 60 60 std::vector<ArcT> arcs; 61 61 62 62 public: 63 63 … … 70 70 71 71 SmartDigraphBase() : nodes(), arcs() { } 72 SmartDigraphBase(const SmartDigraphBase &_g) 72 SmartDigraphBase(const SmartDigraphBase &_g) 73 73 : nodes(_g.nodes), arcs(_g.arcs) { } 74 74 75 75 typedef True NodeNumTag; 76 76 typedef True EdgeNumTag; … … 83 83 84 84 Node addNode() { 85 int n = nodes.size(); 85 int n = nodes.size(); 86 86 nodes.push_back(NodeT()); 87 87 nodes[n].first_in = -1; … … 89 89 return Node(n); 90 90 } 91 91 92 92 Arc addArc(Node u, Node v) { 93 int n = arcs.size(); 93 int n = arcs.size(); 94 94 arcs.push_back(ArcT()); 95 arcs[n].source = u._id; 95 arcs[n].source = u._id; 96 96 arcs[n].target = v._id; 97 97 arcs[n].next_out = nodes[u._id].first_out; … … 116 116 static Arc arcFromId(int id) { return Arc(id);} 117 117 118 bool valid(Node n) const { 119 return n._id >= 0 && n._id < static_cast<int>(nodes.size()); 120 } 121 bool valid(Arc a) const { 122 return a._id >= 0 && a._id < static_cast<int>(arcs.size()); 118 bool valid(Node n) const { 119 return n._id >= 0 && n._id < static_cast<int>(nodes.size()); 120 } 121 bool valid(Arc a) const { 122 return a._id >= 0 && a._id < static_cast<int>(arcs.size()); 123 123 } 124 124 … … 137 137 bool operator<(const Node i) const {return _id < i._id;} 138 138 }; 139 139 140 140 141 141 class Arc { … … 181 181 arc._id = nodes[node._id].first_in; 182 182 } 183 183 184 184 void nextIn(Arc& arc) const { 185 185 arc._id = arcs[arc._id].next_in; … … 223 223 224 224 public: 225 225 226 226 /// Constructor 227 227 228 228 /// Constructor. 229 229 /// 230 230 SmartDigraph() {}; 231 231 232 232 ///Add a new node to the digraph. 233 233 234 234 /// \return the new node. 235 235 /// 236 236 Node addNode() { return Parent::addNode(); } 237 237 238 238 ///Add a new arc to the digraph. 239 239 240 240 ///Add a new arc to the digraph with source node \c s 241 241 ///and target node \c t. 242 242 ///\return the new arc. 243 Arc addArc(const Node& s, const Node& t) { 244 return Parent::addArc(s, t); 243 Arc addArc(const Node& s, const Node& t) { 244 return Parent::addArc(s, t); 245 245 } 246 246 … … 270 270 /// 271 271 /// This function gives back true if the given node is valid, 272 /// ie. it is a real node of the graph. 272 /// ie. it is a real node of the graph. 273 273 /// 274 274 /// \warning A removed node (using Snapshot) could become valid again … … 279 279 /// 280 280 /// This function gives back true if the given arc is valid, 281 /// ie. it is a real arc of the graph. 281 /// ie. it is a real arc of the graph. 282 282 /// 283 283 /// \warning A removed arc (using Snapshot) could become valid again … … 286 286 287 287 ///Clear the digraph. 288 288 289 289 ///Erase all the nodes and arcs from the digraph. 290 290 /// … … 294 294 295 295 ///Split a node. 296 296 297 297 ///This function splits a node. First a new node is added to the digraph, 298 298 ///then the source of each outgoing arc of \c n is moved to this new node. … … 319 319 320 320 public: 321 321 322 322 class Snapshot; 323 323 … … 328 328 while(s.arc_num<arcs.size()) { 329 329 Arc arc = arcFromId(arcs.size()-1); 330 331 332 333 330 Parent::notifier(Arc()).erase(arc); 331 nodes[arcs.back().source].first_out=arcs.back().next_out; 332 nodes[arcs.back().target].first_in=arcs.back().next_in; 333 arcs.pop_back(); 334 334 } 335 335 while(s.node_num<nodes.size()) { 336 336 Node node = nodeFromId(nodes.size()-1); 337 338 339 } 340 } 337 Parent::notifier(Node()).erase(node); 338 nodes.pop_back(); 339 } 340 } 341 341 342 342 public: … … 356 356 ///not the restored digraph or no change. Because the runtime performance 357 357 ///the validity of the snapshot is not stored. 358 class Snapshot 358 class Snapshot 359 359 { 360 360 SmartDigraph *_graph; … … 365 365 public: 366 366 ///Default constructor. 367 367 368 368 ///Default constructor. 369 369 ///To actually make a snapshot you must call save(). … … 371 371 Snapshot() : _graph(0) {} 372 372 ///Constructor that immediately makes a snapshot 373 373 374 374 ///This constructor immediately makes a snapshot of the digraph. 375 375 ///\param _g The digraph we make a snapshot of. 376 376 Snapshot(SmartDigraph &graph) : _graph(&graph) { 377 378 377 node_num=_graph->nodes.size(); 378 arc_num=_graph->arcs.size(); 379 379 } 380 380 … … 386 386 ///call, the previous snapshot gets lost. 387 387 ///\param _g The digraph we make the snapshot of. 388 void save(SmartDigraph &graph) 388 void save(SmartDigraph &graph) 389 389 { 390 391 392 390 _graph=&graph; 391 node_num=_graph->nodes.size(); 392 arc_num=_graph->arcs.size(); 393 393 } 394 394 395 395 ///Undo the changes until a snapshot. 396 396 397 397 ///Undo the changes until a snapshot created by save(). 398 398 /// … … 402 402 void restore() 403 403 { 404 404 _graph->restoreSnapshot(*this); 405 405 } 406 406 }; … … 415 415 int first_out; 416 416 }; 417 417 418 418 struct ArcT { 419 419 int target; … … 425 425 426 426 int first_free_arc; 427 428 public: 429 427 428 public: 429 430 430 typedef SmartGraphBase Digraph; 431 431 … … 433 433 class Arc; 434 434 class Edge; 435 435 436 436 class Node { 437 437 friend class SmartGraphBase; … … 486 486 : nodes(), arcs() {} 487 487 488 489 int maxNodeId() const { return nodes.size()-1; } 488 489 int maxNodeId() const { return nodes.size()-1; } 490 490 int maxEdgeId() const { return arcs.size() / 2 - 1; } 491 491 int maxArcId() const { return arcs.size()-1; } … … 505 505 } 506 506 507 void first(Node& node) const { 507 void first(Node& node) const { 508 508 node._id = nodes.size() - 1; 509 509 } … … 513 513 } 514 514 515 void first(Arc& arc) const { 515 void first(Arc& arc) const { 516 516 arc._id = arcs.size() - 1; 517 517 } … … 521 521 } 522 522 523 void first(Edge& arc) const { 523 void first(Edge& arc) const { 524 524 arc._id = arcs.size() / 2 - 1; 525 525 } … … 562 562 } else { 563 563 arc._id = -1; 564 d = true; 565 } 566 } 567 564 d = true; 565 } 566 } 567 568 568 static int id(Node v) { return v._id; } 569 569 static int id(Arc e) { return e._id; } … … 574 574 static Edge edgeFromId(int id) { return Edge(id);} 575 575 576 bool valid(Node n) const { 577 return n._id >= 0 && n._id < static_cast<int>(nodes.size()); 578 } 579 bool valid(Arc a) const { 576 bool valid(Node n) const { 577 return n._id >= 0 && n._id < static_cast<int>(nodes.size()); 578 } 579 bool valid(Arc a) const { 580 580 return a._id >= 0 && a._id < static_cast<int>(arcs.size()); 581 581 } 582 bool valid(Edge e) const { 583 return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size()); 584 } 585 586 Node addNode() { 582 bool valid(Edge e) const { 583 return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size()); 584 } 585 586 Node addNode() { 587 587 int n = nodes.size(); 588 588 nodes.push_back(NodeT()); 589 589 nodes[n].first_out = -1; 590 590 591 591 return Node(n); 592 592 } 593 593 594 594 Edge addEdge(Node u, Node v) { 595 595 int n = arcs.size(); 596 596 arcs.push_back(ArcT()); 597 597 arcs.push_back(ArcT()); 598 598 599 599 arcs[n].target = u._id; 600 600 arcs[n | 1].target = v._id; … … 603 603 nodes[v._id].first_out = n; 604 604 605 arcs[n | 1].next_out = nodes[u._id].first_out; 605 arcs[n | 1].next_out = nodes[u._id].first_out; 606 606 nodes[u._id].first_out = (n | 1); 607 607 608 608 return Edge(n / 2); 609 609 } 610 610 611 611 void clear() { 612 612 arcs.clear(); … … 626 626 /// that <b> it does support only limited (only stack-like) 627 627 /// node and arc deletions</b>. 628 /// Except from this it conforms to 628 /// Except from this it conforms to 629 629 /// the \ref concepts::Graph "Graph concept". 630 630 /// … … 656 656 657 657 /// Constructor 658 658 659 659 /// Constructor. 660 660 /// … … 662 662 663 663 ///Add a new node to the graph. 664 664 665 665 /// \return the new node. 666 666 /// 667 667 Node addNode() { return Parent::addNode(); } 668 668 669 669 ///Add a new edge to the graph. 670 670 671 671 ///Add a new edge to the graph with node \c s 672 672 ///and \c t. 673 673 ///\return the new edge. 674 Edge addEdge(const Node& s, const Node& t) { 675 return Parent::addEdge(s, t); 674 Edge addEdge(const Node& s, const Node& t) { 675 return Parent::addEdge(s, t); 676 676 } 677 677 … … 679 679 /// 680 680 /// This function gives back true if the given node is valid, 681 /// ie. it is a real node of the graph. 681 /// ie. it is a real node of the graph. 682 682 /// 683 683 /// \warning A removed node (using Snapshot) could become valid again … … 688 688 /// 689 689 /// This function gives back true if the given arc is valid, 690 /// ie. it is a real arc of the graph. 690 /// ie. it is a real arc of the graph. 691 691 /// 692 692 /// \warning A removed arc (using Snapshot) could become valid again … … 697 697 /// 698 698 /// This function gives back true if the given edge is valid, 699 /// ie. it is a real edge of the graph. 699 /// ie. it is a real edge of the graph. 700 700 /// 701 701 /// \warning A removed edge (using Snapshot) could become valid again … … 704 704 705 705 ///Clear the graph. 706 706 707 707 ///Erase all the nodes and edges from the graph. 708 708 /// … … 712 712 713 713 public: 714 714 715 715 class Snapshot; 716 716 … … 729 729 int n=arcs.size()-1; 730 730 Edge arc=edgeFromId(n/2); 731 731 Parent::notifier(Edge()).erase(arc); 732 732 std::vector<Arc> dir; 733 733 dir.push_back(arcFromId(n)); 734 734 dir.push_back(arcFromId(n-1)); 735 736 737 738 739 735 Parent::notifier(Arc()).erase(dir); 736 nodes[arcs[n].target].first_out=arcs[n].next_out; 737 nodes[arcs[n-1].target].first_out=arcs[n-1].next_out; 738 arcs.pop_back(); 739 arcs.pop_back(); 740 740 } 741 741 while(s.node_num<nodes.size()) { 742 742 int n=nodes.size()-1; 743 743 Node node = nodeFromId(n); 744 745 746 } 747 } 744 Parent::notifier(Node()).erase(node); 745 nodes.pop_back(); 746 } 747 } 748 748 749 749 public: … … 764 764 ///not the restored digraph or no change. Because the runtime performance 765 765 ///the validity of the snapshot is not stored. 766 class Snapshot 766 class Snapshot 767 767 { 768 768 SmartGraph *_graph; … … 773 773 public: 774 774 ///Default constructor. 775 775 776 776 ///Default constructor. 777 777 ///To actually make a snapshot you must call save(). … … 779 779 Snapshot() : _graph(0) {} 780 780 ///Constructor that immediately makes a snapshot 781 781 782 782 ///This constructor immediately makes a snapshot of the digraph. 783 783 ///\param g The digraph we make a snapshot of. … … 793 793 ///call, the previous snapshot gets lost. 794 794 ///\param g The digraph we make the snapshot of. 795 void save(SmartGraph &graph) 795 void save(SmartGraph &graph) 796 796 { 797 797 graph.saveSnapshot(*this); … … 799 799 800 800 ///Undo the changes until a snapshot. 801 801 802 802 ///Undo the changes until a snapshot created by save(). 803 803 /// … … 811 811 }; 812 812 }; 813 813 814 814 } //namespace lemon 815 815 -
lemon/time_measure.h
r157 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 65 65 double cstime; 66 66 double rtime; 67 68 void _reset() { 67 68 void _reset() { 69 69 utime = stime = cutime = cstime = rtime = 0; 70 70 } … … 97 97 FILETIME create, exit, kernel, user; 98 98 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) { 99 100 101 102 99 utime = ch * user.dwHighDateTime + cl * user.dwLowDateTime; 100 stime = ch * kernel.dwHighDateTime + cl * kernel.dwLowDateTime; 101 cutime = 0; 102 cstime = 0; 103 103 } else { 104 105 106 107 108 104 rtime = 0; 105 utime = 0; 106 stime = 0; 107 cutime = 0; 108 cstime = 0; 109 109 } 110 #endif 111 } 112 110 #endif 111 } 112 113 113 /// Constructor initializing with zero 114 114 TimeStamp() … … 116 116 ///Constructor initializing with the current time values of the process 117 117 TimeStamp(void *) { stamp();} 118 118 119 119 ///Set every time value to zero 120 120 TimeStamp &reset() {_reset();return *this;} … … 191 191 return t-*this; 192 192 } 193 193 194 194 friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t); 195 195 196 196 ///Gives back the user time of the process 197 197 double userTime() const … … 206 206 ///Gives back the user time of the process' children 207 207 208 ///\note On <tt>WIN32</tt> platform this value is not calculated. 208 ///\note On <tt>WIN32</tt> platform this value is not calculated. 209 209 /// 210 210 double cUserTime() const … … 214 214 ///Gives back the user time of the process' children 215 215 216 ///\note On <tt>WIN32</tt> platform this value is not calculated. 216 ///\note On <tt>WIN32</tt> platform this value is not calculated. 217 217 /// 218 218 double cSystemTime() const … … 224 224 }; 225 225 226 TimeStamp operator*(double b,const TimeStamp &t) 226 TimeStamp operator*(double b,const TimeStamp &t) 227 227 { 228 228 return t*b; 229 229 } 230 230 231 231 ///Prints the time counters 232 232 … … 300 300 TimeStamp start_time; //This is the relativ start-time if the timer 301 301 //is _running, the collected _running time otherwise. 302 302 303 303 void _reset() {if(_running) start_time.stamp(); else start_time.reset();} 304 305 public: 304 305 public: 306 306 ///Constructor. 307 307 … … 332 332 333 333 ///Start the time counters 334 334 335 335 ///This function starts the time counters. 336 336 /// … … 338 338 ///until the same amount of \ref stop() is called. 339 339 ///\sa stop() 340 void start() 340 void start() 341 341 { 342 342 if(_running) _running++; 343 343 else { 344 345 346 347 344 _running=1; 345 TimeStamp t; 346 t.stamp(); 347 start_time=t-start_time; 348 348 } 349 349 } 350 350 351 351 352 352 ///Stop the time counters 353 353 … … 355 355 ///once, then the same number of stop() execution is necessary the really 356 356 ///stop the timer. 357 /// 357 /// 358 358 ///\sa halt() 359 359 ///\sa start() … … 361 361 ///\sa reset() 362 362 363 void stop() 363 void stop() 364 364 { 365 365 if(_running && !--_running) { 366 367 368 366 TimeStamp t; 367 t.stamp(); 368 start_time=t-start_time; 369 369 } 370 370 } … … 384 384 ///\sa reset() 385 385 386 void halt() 386 void halt() 387 387 { 388 388 if(_running) { 389 390 391 392 389 _running=0; 390 TimeStamp t; 391 t.stamp(); 392 start_time=t-start_time; 393 393 } 394 394 } … … 403 403 ///zero). 404 404 int running() { return _running; } 405 406 405 406 407 407 ///Restart the time counters 408 408 … … 410 410 ///a reset() and a start() calls. 411 411 /// 412 void restart() 412 void restart() 413 413 { 414 414 reset(); 415 415 start(); 416 416 } 417 417 418 418 ///@} 419 419 … … 434 434 ///Gives back the ellapsed user time of the process' children 435 435 436 ///\note On <tt>WIN32</tt> platform this value is not calculated. 436 ///\note On <tt>WIN32</tt> platform this value is not calculated. 437 437 /// 438 438 double cUserTime() const … … 442 442 ///Gives back the ellapsed user time of the process' children 443 443 444 ///\note On <tt>WIN32</tt> platform this value is not calculated. 444 ///\note On <tt>WIN32</tt> platform this value is not calculated. 445 445 /// 446 446 double cSystemTime() const … … 488 488 ///\sa NoTimeReport 489 489 ///\todo There is no test case for this 490 class TimeReport : public Timer 490 class TimeReport : public Timer 491 491 { 492 492 std::string _title; … … 499 499 ///\param run Sets whether the timer should start immediately. 500 500 501 TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true) 501 TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true) 502 502 : Timer(run), _title(title), _os(os){} 503 503 ///\e Prints the ellapsed time on destruction. 504 ~TimeReport() 504 ~TimeReport() 505 505 { 506 506 _os << _title << *this << std::endl; 507 507 } 508 508 }; 509 509 510 510 ///'Do nothing' version of \ref TimeReport 511 511 … … 528 528 void start() {} 529 529 void stop() {} 530 void halt() {} 530 void halt() {} 531 531 int running() { return 0; } 532 532 void restart() {} … … 537 537 double realTime() const { return 0; } 538 538 }; 539 539 540 540 ///Tool to measure the running time more exactly. 541 541 542 542 ///This function calls \c f several times and returns the average 543 543 ///running time. The number of the executions will be choosen in such a way … … 551 551 /// total running time will be written into <tt>*full_time</tt>. 552 552 ///\return The average running time of \c f. 553 553 554 554 template<class F> 555 555 TimeStamp runningTimeTest(F f,double min_time=10,unsigned int *num = NULL, … … 567 567 return full/total; 568 568 } 569 570 /// @} 569 570 /// @} 571 571 572 572 -
lemon/tolerance.h
r72 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 32 32 /// \addtogroup misc 33 33 /// @{ 34 34 35 35 ///\brief A class to provide a basic way to 36 36 ///handle the comparison of numbers that are obtained … … 41 41 ///as a result of a probably inexact computation. 42 42 /// 43 ///This is an abstract class, it should be specialized for all 44 ///numerical data types. These specialized classes like 43 ///This is an abstract class, it should be specialized for all 44 ///numerical data types. These specialized classes like 45 45 ///Tolerance<double> may offer additional tuning parameters. 46 46 /// … … 306 306 static Value zero() {return 0;} 307 307 }; 308 308 309 309 310 310 ///Long integer specialization of Tolerance. -
lemon/unionfind.h
r103 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 39 39 /// \brief A \e Union-Find data structure implementation 40 40 /// 41 /// The class implements the \e Union-Find data structure. 41 /// The class implements the \e Union-Find data structure. 42 42 /// The union operation uses rank heuristic, while 43 43 /// the find operation uses path compression. 44 /// This is a very simple but efficient implementation, providing 44 /// This is a very simple but efficient implementation, providing 45 45 /// only four methods: join (union), find, insert and size. 46 46 /// For more features see the \ref UnionFindEnum class. … … 51 51 /// 52 52 /// \pre You need to add all the elements by the \ref insert() 53 /// method. 53 /// method. 54 54 template <typename _ItemIntMap> 55 55 class UnionFind { … … 112 112 /// \brief Inserts a new element into the structure. 113 113 /// 114 /// This method inserts a new element into the data structure. 114 /// This method inserts a new element into the data structure. 115 115 /// 116 116 /// The method returns the index of the new component. … … 124 124 /// \brief Joining the components of element \e a and element \e b. 125 125 /// 126 /// This is the \e union operation of the Union-Find structure. 126 /// This is the \e union operation of the Union-Find structure. 127 127 /// Joins the component of element \e a and component of 128 128 /// element \e b. If \e a and \e b are in the same component then … … 132 132 int kb = repIndex(index[b]); 133 133 134 if ( ka == kb ) 135 134 if ( ka == kb ) 135 return false; 136 136 137 137 if (items[ka] < items[kb]) { 138 139 138 items[ka] += items[kb]; 139 items[kb] = ka; 140 140 } else { 141 142 141 items[kb] += items[ka]; 142 items[ka] = kb; 143 143 } 144 144 return true; … … 174 174 class UnionFindEnum { 175 175 public: 176 176 177 177 typedef _ItemIntMap ItemIntMap; 178 178 typedef typename ItemIntMap::Key Item; 179 179 180 180 private: 181 181 182 182 ItemIntMap& index; 183 183 … … 203 203 int next, prev; 204 204 }; 205 205 206 206 std::vector<ClassT> classes; 207 207 int firstClass, firstFreeClass; … … 209 209 int newClass() { 210 210 if (firstFreeClass == -1) { 211 212 213 211 int cdx = classes.size(); 212 classes.push_back(ClassT()); 213 return cdx; 214 214 } else { 215 216 217 215 int cdx = firstFreeClass; 216 firstFreeClass = classes[firstFreeClass].next; 217 return cdx; 218 218 } 219 219 } … … 221 221 int newItem() { 222 222 if (firstFreeItem == -1) { 223 224 225 223 int idx = items.size(); 224 items.push_back(ItemT()); 225 return idx; 226 226 } else { 227 228 229 227 int idx = firstFreeItem; 228 firstFreeItem = items[firstFreeItem].next; 229 return idx; 230 230 } 231 231 } … … 268 268 items[items[idx].prev].next = items[idx].next; 269 269 items[items[idx].next].prev = items[idx].prev; 270 270 271 271 items[idx].next = firstFreeItem; 272 272 firstFreeItem = idx; … … 279 279 items[ak].prev = items[bk].prev; 280 280 items[bk].prev = tmp; 281 281 282 282 } 283 283 … … 289 289 classes[cls].prev = -1; 290 290 firstClass = cls; 291 } 291 } 292 292 293 293 void unlaceClass(int cls) { … … 300 300 classes[classes[cls].next].prev = classes[cls].prev; 301 301 } 302 302 303 303 classes[cls].next = firstFreeClass; 304 304 firstFreeClass = cls; 305 } 305 } 306 306 307 307 public: 308 308 309 UnionFindEnum(ItemIntMap& _index) 310 : index(_index), items(), firstFreeItem(-1), 311 312 309 UnionFindEnum(ItemIntMap& _index) 310 : index(_index), items(), firstFreeItem(-1), 311 firstClass(-1), firstFreeClass(-1) {} 312 313 313 /// \brief Inserts the given element into a new component. 314 314 /// … … 333 333 334 334 firstClass = cdx; 335 335 336 336 return cdx; 337 337 } … … 340 340 /// 341 341 /// This methods inserts the element \e a into the component of the 342 /// element \e comp. 342 /// element \e comp. 343 343 void insert(const Item& item, int cls) { 344 344 int rdx = classes[cls].firstItem; … … 373 373 /// \brief Joining the component of element \e a and element \e b. 374 374 /// 375 /// This is the \e union operation of the Union-Find structure. 375 /// This is the \e union operation of the Union-Find structure. 376 376 /// Joins the component of element \e a and component of 377 377 /// element \e b. If \e a and \e b are in the same component then … … 383 383 384 384 if (ak == bk) { 385 385 return -1; 386 386 } 387 387 … … 392 392 393 393 if (classes[acx].size > classes[bcx].size) { 394 395 394 classes[acx].size += classes[bcx].size; 395 items[bk].parent = ak; 396 396 unlaceClass(bcx); 397 397 rcx = acx; 398 398 } else { 399 400 399 classes[bcx].size += classes[acx].size; 400 items[ak].parent = bk; 401 401 unlaceClass(acx); 402 402 rcx = bcx; 403 403 } 404 404 spliceItems(ak, bk); … … 414 414 } 415 415 416 /// \brief Splits up the component. 416 /// \brief Splits up the component. 417 417 /// 418 418 /// Splitting the component into singleton components (component … … 424 424 int next = items[idx].next; 425 425 426 427 428 int cdx = newClass(); 426 singletonItem(idx); 427 428 int cdx = newClass(); 429 429 items[idx].parent = ~cdx; 430 430 431 432 433 434 431 laceClass(cdx); 432 classes[cdx].size = 1; 433 classes[cdx].firstItem = idx; 434 435 435 idx = next; 436 436 } … … 440 440 441 441 classes[~(items[idx].parent)].size = 1; 442 442 443 443 } 444 444 … … 458 458 int cdx = classIndex(idx); 459 459 if (idx == fdx) { 460 461 462 463 460 unlaceClass(cdx); 461 items[idx].next = firstFreeItem; 462 firstFreeItem = idx; 463 return; 464 464 } else { 465 466 467 468 469 470 471 472 473 474 475 465 classes[cdx].firstItem = fdx; 466 --classes[cdx].size; 467 items[fdx].parent = ~cdx; 468 469 unlaceItem(idx); 470 idx = items[fdx].next; 471 while (idx != fdx) { 472 items[idx].parent = fdx; 473 idx = items[idx].next; 474 } 475 476 476 } 477 477 … … 515 515 /// Constructor to get invalid iterator 516 516 ClassIt(Invalid) : unionFind(0), cdx(-1) {} 517 517 518 518 /// \brief Increment operator 519 519 /// … … 523 523 return *this; 524 524 } 525 525 526 526 /// \brief Conversion operator 527 527 /// … … 534 534 /// 535 535 /// Equality operator 536 bool operator==(const ClassIt& i) { 536 bool operator==(const ClassIt& i) { 537 537 return i.cdx == cdx; 538 538 } … … 541 541 /// 542 542 /// Inequality operator 543 bool operator!=(const ClassIt& i) { 543 bool operator!=(const ClassIt& i) { 544 544 return i.cdx != cdx; 545 545 } 546 546 547 547 private: 548 548 const UnionFindEnum* unionFind; … … 578 578 /// Constructor to get invalid iterator 579 579 ItemIt(Invalid) : unionFind(0), idx(-1) {} 580 580 581 581 /// \brief Increment operator 582 582 /// … … 587 587 return *this; 588 588 } 589 589 590 590 /// \brief Conversion operator 591 591 /// … … 598 598 /// 599 599 /// Equality operator 600 bool operator==(const ItemIt& i) { 600 bool operator==(const ItemIt& i) { 601 601 return i.idx == idx; 602 602 } … … 605 605 /// 606 606 /// Inequality operator 607 bool operator!=(const ItemIt& i) { 607 bool operator!=(const ItemIt& i) { 608 608 return i.idx != idx; 609 609 } 610 610 611 611 private: 612 612 const UnionFindEnum* unionFind; … … 631 631 class ExtendFindEnum { 632 632 public: 633 633 634 634 typedef _ItemIntMap ItemIntMap; 635 635 typedef typename ItemIntMap::Key Item; 636 636 637 637 private: 638 638 639 639 ItemIntMap& index; 640 640 … … 659 659 int newClass() { 660 660 if (firstFreeClass != -1) { 661 662 663 661 int cdx = firstFreeClass; 662 firstFreeClass = classes[cdx].next; 663 return cdx; 664 664 } else { 665 666 665 classes.push_back(ClassT()); 666 return classes.size() - 1; 667 667 } 668 668 } … … 670 670 int newItem() { 671 671 if (firstFreeItem != -1) { 672 673 674 672 int idx = firstFreeItem; 673 firstFreeItem = items[idx].next; 674 return idx; 675 675 } else { 676 677 676 items.push_back(ItemT()); 677 return items.size() - 1; 678 678 } 679 679 } … … 682 682 683 683 /// \brief Constructor 684 ExtendFindEnum(ItemIntMap& _index) 685 : index(_index), items(), firstFreeItem(-1), 686 687 684 ExtendFindEnum(ItemIntMap& _index) 685 : index(_index), items(), firstFreeItem(-1), 686 classes(), firstClass(-1), firstFreeClass(-1) {} 687 688 688 /// \brief Inserts the given element into a new component. 689 689 /// … … 695 695 classes[cdx].next = firstClass; 696 696 if (firstClass != -1) { 697 697 classes[firstClass].prev = cdx; 698 698 } 699 699 firstClass = cdx; 700 700 701 701 int idx = newItem(); 702 702 items[idx].item = item; … … 708 708 709 709 index.set(item, idx); 710 710 711 711 return cdx; 712 712 } … … 751 751 return items[classes[cls].firstItem].item; 752 752 } 753 753 754 754 /// \brief Removes the given element from the structure. 755 755 /// … … 762 762 int idx = index[item]; 763 763 int cdx = items[idx].cls; 764 764 765 765 if (idx == items[idx].next) { 766 767 classes[classes[cdx].prev].next = classes[cdx].next; 768 769 770 771 772 classes[classes[cdx].next].prev = classes[cdx].prev; 773 774 775 766 if (classes[cdx].prev != -1) { 767 classes[classes[cdx].prev].next = classes[cdx].next; 768 } else { 769 firstClass = classes[cdx].next; 770 } 771 if (classes[cdx].next != -1) { 772 classes[classes[cdx].next].prev = classes[cdx].prev; 773 } 774 classes[cdx].next = firstFreeClass; 775 firstFreeClass = cdx; 776 776 } else { 777 778 779 777 classes[cdx].firstItem = items[idx].next; 778 items[items[idx].next].prev = items[idx].prev; 779 items[items[idx].prev].next = items[idx].next; 780 780 } 781 781 items[idx].next = firstFreeItem; 782 782 firstFreeItem = idx; 783 784 } 785 786 783 784 } 785 786 787 787 /// \brief Removes the component of the given element from the structure. 788 788 /// … … 797 797 798 798 if (classes[cdx].prev != -1) { 799 classes[classes[cdx].prev].next = classes[cdx].next; 799 classes[classes[cdx].prev].next = classes[cdx].next; 800 800 } else { 801 801 firstClass = classes[cdx].next; 802 802 } 803 803 if (classes[cdx].next != -1) { 804 classes[classes[cdx].next].prev = classes[cdx].prev; 804 classes[classes[cdx].next].prev = classes[cdx].prev; 805 805 } 806 806 classes[cdx].next = firstFreeClass; … … 825 825 /// Constructor to get invalid iterator 826 826 ClassIt(Invalid) : extendFind(0), cdx(-1) {} 827 827 828 828 /// \brief Increment operator 829 829 /// … … 833 833 return *this; 834 834 } 835 835 836 836 /// \brief Conversion operator 837 837 /// … … 844 844 /// 845 845 /// Equality operator 846 bool operator==(const ClassIt& i) { 846 bool operator==(const ClassIt& i) { 847 847 return i.cdx == cdx; 848 848 } … … 851 851 /// 852 852 /// Inequality operator 853 bool operator!=(const ClassIt& i) { 853 bool operator!=(const ClassIt& i) { 854 854 return i.cdx != cdx; 855 855 } 856 856 857 857 private: 858 858 const ExtendFindEnum* extendFind; … … 888 888 /// Constructor to get invalid iterator 889 889 ItemIt(Invalid) : extendFind(0), idx(-1) {} 890 890 891 891 /// \brief Increment operator 892 892 /// … … 894 894 ItemIt& operator++() { 895 895 idx = extendFind->items[idx].next; 896 896 if (fdx == idx) idx = -1; 897 897 return *this; 898 898 } 899 899 900 900 /// \brief Conversion operator 901 901 /// … … 908 908 /// 909 909 /// Equality operator 910 bool operator==(const ItemIt& i) { 910 bool operator==(const ItemIt& i) { 911 911 return i.idx == idx; 912 912 } … … 915 915 /// 916 916 /// Inequality operator 917 bool operator!=(const ItemIt& i) { 917 bool operator!=(const ItemIt& i) { 918 918 return i.idx != idx; 919 919 } 920 920 921 921 private: 922 922 const ExtendFindEnum* extendFind; … … 950 950 /// method. 951 951 /// 952 template <typename _Value, typename _ItemIntMap, 952 template <typename _Value, typename _ItemIntMap, 953 953 typename _Comp = std::less<_Value> > 954 954 class HeapUnionFind { 955 955 public: 956 956 957 957 typedef _Value Value; 958 958 typedef typename _ItemIntMap::Key Item; … … 1055 1055 id = nodes[id].next; 1056 1056 while (depth--) { 1057 id = nodes[id].left; 1057 id = nodes[id].left; 1058 1058 } 1059 1059 return id; … … 1133 1133 nodes[kd].right = nodes[id].prev; 1134 1134 nodes[nodes[id].prev].next = -1; 1135 1135 1136 1136 nodes[jd].left = id; 1137 1137 nodes[id].prev = -1; … … 1142 1142 id = nodes[id].next; 1143 1143 ++num; 1144 } 1144 } 1145 1145 nodes[kd].size -= num; 1146 1146 nodes[jd].size = num; … … 1166 1166 int jd = ~(classes[id].parent); 1167 1167 while (nodes[jd].left != -1) { 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 } 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 } 1205 } 1168 int kd = nodes[jd].left; 1169 if (nodes[jd].size == 1) { 1170 if (nodes[jd].parent < 0) { 1171 classes[id].parent = ~kd; 1172 classes[id].depth -= 1; 1173 nodes[kd].parent = ~id; 1174 deleteNode(jd); 1175 jd = kd; 1176 } else { 1177 int pd = nodes[jd].parent; 1178 if (nodes[nodes[jd].next].size < cmax) { 1179 pushLeft(nodes[jd].next, nodes[jd].left); 1180 if (less(nodes[jd].left, nodes[jd].next)) { 1181 nodes[nodes[jd].next].prio = nodes[nodes[jd].left].prio; 1182 nodes[nodes[jd].next].item = nodes[nodes[jd].left].item; 1183 } 1184 popLeft(pd); 1185 deleteNode(jd); 1186 jd = pd; 1187 } else { 1188 int ld = nodes[nodes[jd].next].left; 1189 popLeft(nodes[jd].next); 1190 pushRight(jd, ld); 1191 if (less(ld, nodes[jd].left)) { 1192 nodes[jd].item = nodes[ld].item; 1193 nodes[jd].prio = nodes[jd].prio; 1194 } 1195 if (nodes[nodes[jd].next].item == nodes[ld].item) { 1196 setPrio(nodes[jd].next); 1197 } 1198 jd = nodes[jd].left; 1199 } 1200 } 1201 } else { 1202 jd = nodes[jd].left; 1203 } 1204 } 1205 } 1206 1206 1207 1207 void repairRight(int id) { 1208 1208 int jd = ~(classes[id].parent); 1209 1209 while (nodes[jd].right != -1) { 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 } 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1210 int kd = nodes[jd].right; 1211 if (nodes[jd].size == 1) { 1212 if (nodes[jd].parent < 0) { 1213 classes[id].parent = ~kd; 1214 classes[id].depth -= 1; 1215 nodes[kd].parent = ~id; 1216 deleteNode(jd); 1217 jd = kd; 1218 } else { 1219 int pd = nodes[jd].parent; 1220 if (nodes[nodes[jd].prev].size < cmax) { 1221 pushRight(nodes[jd].prev, nodes[jd].right); 1222 if (less(nodes[jd].right, nodes[jd].prev)) { 1223 nodes[nodes[jd].prev].prio = nodes[nodes[jd].right].prio; 1224 nodes[nodes[jd].prev].item = nodes[nodes[jd].right].item; 1225 } 1226 popRight(pd); 1227 deleteNode(jd); 1228 jd = pd; 1229 } else { 1230 int ld = nodes[nodes[jd].prev].right; 1231 popRight(nodes[jd].prev); 1232 pushLeft(jd, ld); 1233 if (less(ld, nodes[jd].right)) { 1234 nodes[jd].item = nodes[ld].item; 1235 nodes[jd].prio = nodes[jd].prio; 1236 } 1237 if (nodes[nodes[jd].prev].item == nodes[ld].item) { 1238 setPrio(nodes[jd].prev); 1239 } 1240 jd = nodes[jd].right; 1241 } 1242 } 1243 } else { 1244 jd = nodes[jd].right; 1245 } 1246 1246 } 1247 1247 } … … 1277 1277 /// \brief Constructs the union-find. 1278 1278 /// 1279 /// Constructs the union-find. 1279 /// Constructs the union-find. 1280 1280 /// \brief _index The index map of the union-find. The data 1281 1281 /// structure uses internally for store references. 1282 HeapUnionFind(ItemIntMap& _index) 1283 : index(_index), first_class(-1), 1284 1282 HeapUnionFind(ItemIntMap& _index) 1283 : index(_index), first_class(-1), 1284 first_free_class(-1), first_free_node(-1) {} 1285 1285 1286 1286 /// \brief Insert a new node into a new component. … … 1304 1304 nodes[id].item = item; 1305 1305 index[item] = id; 1306 1306 1307 1307 int class_id = newClass(); 1308 1308 classes[class_id].parent = ~id; … … 1311 1311 classes[class_id].left = -1; 1312 1312 classes[class_id].right = -1; 1313 1313 1314 1314 if (first_class != -1) { 1315 1315 classes[first_class].prev = class_id; … … 1320 1320 1321 1321 nodes[id].parent = ~class_id; 1322 1322 1323 1323 return class_id; 1324 1324 } … … 1333 1333 return findClass(index[item]); 1334 1334 } 1335 1335 1336 1336 /// \brief Joins the classes. 1337 1337 /// … … 1372 1372 } 1373 1373 classes[classes[l].prev].next = classes[l].next; 1374 1374 1375 1375 classes[l].prev = -1; 1376 1376 classes[l].next = -1; … … 1378 1378 classes[l].depth = leftNode(l); 1379 1379 classes[l].parent = class_id; 1380 1380 1381 1381 } 1382 1382 … … 1456 1456 pushLeft(new_parent, ~(classes[l].parent)); 1457 1457 setPrio(new_parent); 1458 1458 1459 1459 classes[r].parent = ~new_parent; 1460 1460 classes[r].depth += 1; … … 1471 1471 classes[l].depth = classes[r].depth; 1472 1472 } else { 1473 if (classes[l].depth != 0 && 1474 nodes[~(classes[l].parent)].size + 1473 if (classes[l].depth != 0 && 1474 nodes[~(classes[l].parent)].size + 1475 1475 nodes[~(classes[r].parent)].size <= cmax) { 1476 1476 splice(~(classes[l].parent), ~(classes[r].parent)); 1477 1477 deleteNode(~(classes[r].parent)); 1478 1478 if (less(~(classes[r].parent), ~(classes[l].parent))) { 1479 nodes[~(classes[l].parent)].prio = 1479 nodes[~(classes[l].parent)].prio = 1480 1480 nodes[~(classes[r].parent)].prio; 1481 nodes[~(classes[l].parent)].item = 1481 nodes[~(classes[l].parent)].item = 1482 1482 nodes[~(classes[r].parent)].item; 1483 1483 } … … 1488 1488 pushRight(new_parent, ~(classes[r].parent)); 1489 1489 setPrio(new_parent); 1490 1490 1491 1491 classes[l].parent = ~new_parent; 1492 1492 classes[l].depth += 1; … … 1543 1543 classes[first_class].prev = classes[id].right; 1544 1544 first_class = classes[id].left; 1545 1545 1546 1546 if (classes[id].next != -1) { 1547 1547 classes[classes[id].next].prev = classes[id].prev; 1548 1548 } 1549 1549 classes[classes[id].prev].next = classes[id].next; 1550 1550 1551 1551 deleteClass(id); 1552 1552 } … … 1558 1558 l = nodes[l].parent; 1559 1559 } 1560 int r = l; 1560 int r = l; 1561 1561 while (nodes[l].parent >= 0) { 1562 1562 l = nodes[l].parent; … … 1581 1581 repairRight(~(nodes[l].parent)); 1582 1582 repairLeft(cs[i]); 1583 1583 1584 1584 *out++ = cs[i]; 1585 1585 } … … 1604 1604 } 1605 1605 } 1606 1606 1607 1607 /// \brief Increase the priority of the current item. 1608 1608 /// … … 1631 1631 } 1632 1632 } 1633 1633 1634 1634 /// \brief Gives back the minimum priority of the class. 1635 1635 /// … … 1647 1647 1648 1648 /// \brief Gives back a representant item of the class. 1649 /// 1649 /// 1650 1650 /// The representant is indpendent from the priorities of the 1651 /// items. 1651 /// items. 1652 1652 /// \return Gives back a representant item of the class. 1653 1653 const Item& classRep(int id) const { … … 1675 1675 const HeapUnionFind* _huf; 1676 1676 int _id, _lid; 1677 1677 1678 1678 public: 1679 1679 1680 /// \brief Default constructor 1681 /// 1682 /// Default constructor 1680 /// \brief Default constructor 1681 /// 1682 /// Default constructor 1683 1683 ItemIt() {} 1684 1684 … … 1696 1696 _id = _huf->leftNode(id); 1697 1697 _lid = -1; 1698 } 1699 } 1700 1698 } 1699 } 1700 1701 1701 /// \brief Increment operator 1702 1702 /// … … 1713 1713 return _huf->nodes[_id].item; 1714 1714 } 1715 1715 1716 1716 /// \brief Equality operator 1717 1717 /// 1718 1718 /// Equality operator 1719 bool operator==(const ItemIt& i) { 1719 bool operator==(const ItemIt& i) { 1720 1720 return i._id == _id; 1721 1721 } … … 1724 1724 /// 1725 1725 /// Inequality operator 1726 bool operator!=(const ItemIt& i) { 1726 bool operator!=(const ItemIt& i) { 1727 1727 return i._id != _id; 1728 1728 } … … 1731 1731 /// 1732 1732 /// Equality operator 1733 bool operator==(Invalid) { 1733 bool operator==(Invalid) { 1734 1734 return _id == _lid; 1735 1735 } … … 1738 1738 /// 1739 1739 /// Inequality operator 1740 bool operator!=(Invalid) { 1740 bool operator!=(Invalid) { 1741 1741 return _id != _lid; 1742 1742 } 1743 1743 1744 1744 }; 1745 1745 1746 1746 /// \brief Class iterator 1747 1747 /// 1748 /// The iterator stores 1748 /// The iterator stores 1749 1749 class ClassIt { 1750 1750 private: … … 1755 1755 public: 1756 1756 1757 ClassIt(const HeapUnionFind& huf) 1757 ClassIt(const HeapUnionFind& huf) 1758 1758 : _huf(&huf), _id(huf.first_class) {} 1759 1759 1760 ClassIt(const HeapUnionFind& huf, int cls) 1760 ClassIt(const HeapUnionFind& huf, int cls) 1761 1761 : _huf(&huf), _id(huf.classes[cls].left) {} 1762 1762 1763 1763 ClassIt(Invalid) : _huf(0), _id(-1) {} 1764 1764 1765 1765 const ClassIt& operator++() { 1766 1766 _id = _huf->classes[_id].next; 1767 1767 return *this; 1768 1768 } 1769 1769 … … 1771 1771 /// 1772 1772 /// Equality operator 1773 bool operator==(const ClassIt& i) { 1773 bool operator==(const ClassIt& i) { 1774 1774 return i._id == _id; 1775 1775 } … … 1778 1778 /// 1779 1779 /// Inequality operator 1780 bool operator!=(const ClassIt& i) { 1780 bool operator!=(const ClassIt& i) { 1781 1781 return i._id != _id; 1782 } 1783 1782 } 1783 1784 1784 operator int() const { 1785 1786 } 1787 1785 return _id; 1786 } 1787 1788 1788 }; 1789 1789 -
test/bfs_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 28 28 using namespace lemon; 29 29 30 void checkBfsCompile() 30 void checkBfsCompile() 31 31 { 32 32 typedef concepts::Digraph Digraph; 33 33 typedef Bfs<Digraph> BType; 34 34 35 35 Digraph G; 36 36 Digraph::Node n; … … 41 41 BType::PredMap p(G); 42 42 // BType::PredNodeMap pn(G); 43 43 44 44 BType bfs_test(G); 45 45 46 46 bfs_test.run(n); 47 47 48 48 l = bfs_test.dist(n); 49 49 e = bfs_test.predArc(n); … … 57 57 } 58 58 59 void checkBfsFunctionCompile() 59 void checkBfsFunctionCompile() 60 60 { 61 61 typedef int VType; … … 63 63 typedef Digraph::Arc Arc; 64 64 typedef Digraph::Node Node; 65 65 66 66 Digraph g; 67 67 bfs(g,Node()).run(); … … 82 82 Node s, t; 83 83 PetStruct<Digraph> ps = addPetersen(G, 5); 84 84 85 85 s=ps.outer[2]; 86 86 t=ps.inner[0]; 87 87 88 88 Bfs<Digraph> bfs_test(G); 89 89 bfs_test.run(s); 90 90 91 91 check(bfs_test.dist(t)==3,"Bfs found a wrong path." << bfs_test.dist(t)); 92 92 … … 96 96 check(pathSource(G, p) == s,"path() found a wrong path."); 97 97 check(pathTarget(G, p) == t,"path() found a wrong path."); 98 98 99 99 100 100 for(ArcIt e(G); e==INVALID; ++e) { … … 102 102 Node v=G.target(e); 103 103 check( !bfs_test.reached(u) || 104 105 104 (bfs_test.dist(v) > bfs_test.dist(u)+1), 105 "Wrong output."); 106 106 } 107 107 … … 113 113 check(u==bfs_test.predNode(v),"Wrong tree."); 114 114 check(bfs_test.dist(v) - bfs_test.dist(u) == 1, 115 "Wrong distance. Difference: " 116 << std::abs(bfs_test.dist(v) - bfs_test.dist(u) 117 115 "Wrong distance. Difference: " 116 << std::abs(bfs_test.dist(v) - bfs_test.dist(u) 117 - 1)); 118 118 } 119 119 } -
test/counter_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 76 76 void init(std::vector<int>& v) { 77 77 v[0] = 10; v[1] = 60; v[2] = 20; v[3] = 90; v[4] = 100; 78 v[5] = 80; v[6] = 40; v[7] = 30; v[8] = 50; v[9] = 70; 78 v[5] = 80; v[6] = 40; v[7] = 30; v[8] = 50; v[9] = 70; 79 79 } 80 80 … … 83 83 counterTest<Counter>(); 84 84 counterTest<NoCounter>(); 85 85 86 86 std::vector<int> x(10); 87 87 init(x); bubbleSort(x); -
test/dfs_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 28 28 using namespace lemon; 29 29 30 void checkDfsCompile() 30 void checkDfsCompile() 31 31 { 32 32 typedef concepts::Digraph Digraph; 33 33 typedef Dfs<Digraph> DType; 34 34 35 35 Digraph G; 36 36 Digraph::Node n; … … 41 41 DType::PredMap p(G); 42 42 // DType::PredNodeMap pn(G); 43 43 44 44 DType dfs_test(G); 45 45 46 46 dfs_test.run(n); 47 47 48 48 l = dfs_test.dist(n); 49 49 e = dfs_test.predArc(n); … … 57 57 } 58 58 59 void checkDfsFunctionCompile() 59 void checkDfsFunctionCompile() 60 60 { 61 61 typedef int VType; … … 63 63 typedef Digraph::Arc Arc; 64 64 typedef Digraph::Node Node; 65 65 66 66 Digraph g; 67 67 dfs(g,Node()).run(); … … 72 72 .reachedMap(concepts::ReadWriteMap<Node,bool>()) 73 73 .processedMap(concepts::WriteMap<Node,bool>()) 74 .run(Node()); 74 .run(Node()); 75 75 } 76 76 … … 82 82 Node s, t; 83 83 PetStruct<Digraph> ps = addPetersen(G, 5); 84 84 85 85 s=ps.outer[2]; 86 86 t=ps.inner[0]; 87 87 88 88 Dfs<Digraph> dfs_test(G); 89 dfs_test.run(s); 90 89 dfs_test.run(s); 90 91 91 Path<Digraph> p = dfs_test.path(t); 92 92 check(p.length() == dfs_test.dist(t),"path() found a wrong path."); … … 94 94 check(pathSource(G, p) == s,"path() found a wrong path."); 95 95 check(pathTarget(G, p) == t,"path() found a wrong path."); 96 96 97 97 for(NodeIt v(G); v!=INVALID; ++v) { 98 98 check(dfs_test.reached(v),"Each node should be reached."); … … 102 102 check(u==dfs_test.predNode(v),"Wrong tree."); 103 103 check(dfs_test.dist(v) - dfs_test.dist(u) == 1, 104 "Wrong distance. (" << dfs_test.dist(u) << "->" 105 104 "Wrong distance. (" << dfs_test.dist(u) << "->" 105 <<dfs_test.dist(v) << ')'); 106 106 } 107 107 } -
test/digraph_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 34 34 checkConcept<BaseDigraphComponent, BaseDigraphComponent >(); 35 35 36 checkConcept<IDableDigraphComponent<>, 36 checkConcept<IDableDigraphComponent<>, 37 37 IDableDigraphComponent<> >(); 38 38 39 checkConcept<IterableDigraphComponent<>, 39 checkConcept<IterableDigraphComponent<>, 40 40 IterableDigraphComponent<> >(); 41 41 42 checkConcept<MappableDigraphComponent<>, 42 checkConcept<MappableDigraphComponent<>, 43 43 MappableDigraphComponent<> >(); 44 44 } -
test/dijkstra_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 29 29 using namespace lemon; 30 30 31 void checkDijkstraCompile() 31 void checkDijkstraCompile() 32 32 { 33 33 typedef int VType; … … 35 35 typedef concepts::ReadMap<Digraph::Arc,VType> LengthMap; 36 36 typedef Dijkstra<Digraph, LengthMap> DType; 37 37 38 38 Digraph G; 39 39 Digraph::Node n; … … 61 61 } 62 62 63 void checkDijkstraFunctionCompile() 63 void checkDijkstraFunctionCompile() 64 64 { 65 65 typedef int VType; … … 68 68 typedef Digraph::Node Node; 69 69 typedef concepts::ReadMap<Digraph::Arc,VType> LengthMap; 70 70 71 71 Digraph g; 72 72 dijkstra(g,LengthMap(),Node()).run(); … … 79 79 80 80 template <class Digraph> 81 void checkDijkstra() { 81 void checkDijkstra() { 82 82 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph); 83 83 typedef typename Digraph::template ArcMap<int> LengthMap; … … 87 87 LengthMap length(G); 88 88 PetStruct<Digraph> ps = addPetersen(G, 5); 89 89 90 90 for(int i=0;i<5;i++) { 91 91 length[ps.outcir[i]]=4; … … 95 95 s=ps.outer[0]; 96 96 t=ps.inner[1]; 97 98 Dijkstra<Digraph, LengthMap> 99 97 98 Dijkstra<Digraph, LengthMap> 99 dijkstra_test(G, length); 100 100 dijkstra_test.run(s); 101 101 102 102 check(dijkstra_test.dist(t)==13,"Dijkstra found a wrong path."); 103 103 … … 107 107 check(pathSource(G, p) == s,"path() found a wrong path."); 108 108 check(pathTarget(G, p) == t,"path() found a wrong path."); 109 109 110 110 for(ArcIt e(G); e!=INVALID; ++e) { 111 111 Node u=G.source(e); 112 112 Node v=G.target(e); 113 113 check( !dijkstra_test.reached(u) || (dijkstra_test.dist(v) - dijkstra_test.dist(u) <= length[e]), 114 114 "dist(target)-dist(source)-arc_length= " << dijkstra_test.dist(v) - dijkstra_test.dist(u) - length[e]); 115 115 } 116 116 … … 122 122 check(u==dijkstra_test.predNode(v),"Wrong tree."); 123 123 check(dijkstra_test.dist(v) - dijkstra_test.dist(u) == length[e], 124 124 "Wrong distance! Difference: " << std::abs(dijkstra_test.dist(v) - dijkstra_test.dist(u) - length[e])); 125 125 } 126 126 } 127 127 128 128 { 129 129 NullMap<Node,Arc> myPredMap; -
test/dim_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
test/error_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 59 59 60 60 static int cnt = 0; 61 void my_assert_handler(const char*, int, const char*, 62 61 void my_assert_handler(const char*, int, const char*, 62 const char*, const char*) { 63 63 ++cnt; 64 64 } -
test/graph_copy_test.cc
r200 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 123 123 } 124 124 } 125 125 126 126 ListGraph to; 127 127 ListGraph::NodeMap<int> tnm(to); … … 161 161 check(ecr[er[it]] == it, "Wrong copy."); 162 162 check(fem[it] == tem[er[it]], "Wrong copy."); 163 check(nr[from.u(it)] == to.u(er[it]) || nr[from.u(it)] == to.v(er[it]), 164 165 check(nr[from.v(it)] == to.u(er[it]) || nr[from.v(it)] == to.v(er[it]), 166 167 check((from.u(it) != from.v(it)) == (to.u(er[it]) != to.v(er[it])), 168 163 check(nr[from.u(it)] == to.u(er[it]) || nr[from.u(it)] == to.v(er[it]), 164 "Wrong copy."); 165 check(nr[from.v(it)] == to.u(er[it]) || nr[from.v(it)] == to.v(er[it]), 166 "Wrong copy."); 167 check((from.u(it) != from.v(it)) == (to.u(er[it]) != to.v(er[it])), 168 "Wrong copy."); 169 169 } 170 170 … … 189 189 graph_copy_test(); 190 190 191 return 0; 191 return 0; 192 192 } -
test/graph_maps_test.h
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 72 72 for (int i = 0; i < num; ++i) { 73 73 for (int j = 0; j < i; ++j) { 74 74 arcs.push_back(graph.addArc(nodes[i], nodes[j])); 75 75 } 76 76 } … … 85 85 for (int i = 0; i < num; ++i) { 86 86 for (int j = i + 1; j < num; ++j) { 87 88 87 arcs.push_back(graph.addArc(nodes[i], nodes[j])); 88 map[arcs.back()] = 23; 89 89 check(map[arcs.back()] == 23, "Wrong operator[]."); 90 90 } … … 114 114 for (int i = 0; i < num; ++i) { 115 115 for (int j = 0; j < i; ++j) { 116 116 edges.push_back(graph.addEdge(nodes[i], nodes[j])); 117 117 } 118 118 } … … 127 127 for (int i = 0; i < num; ++i) { 128 128 for (int j = i + 1; j < num; ++j) { 129 130 129 edges.push_back(graph.addEdge(nodes[i], nodes[j])); 130 map[edges.back()] = 23; 131 131 check(map[edges.back()] == 23, "Wrong operator[]."); 132 132 } -
test/graph_test.cc
r171 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 34 34 checkConcept<BaseGraphComponent, BaseGraphComponent >(); 35 35 36 checkConcept<IDableGraphComponent<>, 36 checkConcept<IDableGraphComponent<>, 37 37 IDableGraphComponent<> >(); 38 38 39 checkConcept<IterableGraphComponent<>, 39 checkConcept<IterableGraphComponent<>, 40 40 IterableGraphComponent<> >(); 41 41 42 checkConcept<MappableGraphComponent<>, 42 checkConcept<MappableGraphComponent<>, 43 43 MappableGraphComponent<> >(); 44 44 } … … 135 135 // } 136 136 // } 137 137 138 138 // for (int i = 0; i < w; ++i) { 139 139 // for (int j = 0; j < h - 1; ++j) { … … 155 155 // for (int i = 0; i < w - 1; ++i) { 156 156 // check(g.source(g.right(g(i, j))) == g(i, j), "Wrong right"); 157 // check(g.target(g.right(g(i, j))) == g(i + 1, j), "Wrong right"); 158 // } 159 // check(g.right(g(w - 1, j)) == INVALID, "Wrong right"); 157 // check(g.target(g.right(g(i, j))) == g(i + 1, j), "Wrong right"); 158 // } 159 // check(g.right(g(w - 1, j)) == INVALID, "Wrong right"); 160 160 // } 161 161 … … 163 163 // for (int i = 1; i < w; ++i) { 164 164 // check(g.source(g.left(g(i, j))) == g(i, j), "Wrong left"); 165 // check(g.target(g.left(g(i, j))) == g(i - 1, j), "Wrong left"); 166 // } 167 // check(g.left(g(0, j)) == INVALID, "Wrong left"); 165 // check(g.target(g.left(g(i, j))) == g(i - 1, j), "Wrong left"); 166 // } 167 // check(g.left(g(0, j)) == INVALID, "Wrong left"); 168 168 // } 169 169 // } -
test/graph_test.h
r171 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 218 218 n.incir.push_back(G.addEdge(n.inner[i],n.inner[(i+2)%num])); 219 219 } 220 220 221 221 return n; 222 222 } … … 247 247 checkBidirPetersen(G, num); 248 248 } 249 249 250 250 template <class Graph> 251 251 void checkGraph() { -
test/graph_utils_test.cc
r171 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 141 141 { 142 142 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph); 143 143 144 144 const int nodeNum = 10; 145 145 const int arcNum = 100; … … 156 156 } 157 157 for (int i = 0; i < nodeNum; ++i) { 158 check(inDeg[nodes[i]] == countInArcs(digraph, nodes[i]), 158 check(inDeg[nodes[i]] == countInArcs(digraph, nodes[i]), 159 159 "Wrong in degree map"); 160 160 } 161 161 for (int i = 0; i < nodeNum; ++i) { 162 check(outDeg[nodes[i]] == countOutArcs(digraph, nodes[i]), 162 check(outDeg[nodes[i]] == countOutArcs(digraph, nodes[i]), 163 163 "Wrong out degree map"); 164 164 } … … 173 173 Node n1=g.addNode(); 174 174 Node n2=g.addNode(); 175 175 176 176 InDegMap<Digraph> ind(g); 177 177 178 178 g.addArc(n1,n2); 179 179 180 180 typename Digraph::Snapshot snap(g); 181 181 182 182 OutDegMap<Digraph> outd(g); 183 183 184 184 check(ind[n1]==0 && ind[n2]==1, "Wrong InDegMap value."); 185 185 check(outd[n1]==1 && outd[n2]==0, "Wrong OutDegMap value."); -
test/heap_test.cc
r203 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 41 41 DIGRAPH_TYPEDEFS(Digraph); 42 42 43 char test_lgf[] = 44 "@nodes\n" 45 "label\n" 46 "0\n" 47 "1\n" 48 "2\n" 49 "3\n" 50 "4\n" 51 "5\n" 52 "6\n" 53 "7\n" 54 "8\n" 55 "9\n" 56 "@arcs\n" 57 " label capacity\n"58 "0 5 0 94\n"59 "3 9 1 11\n"60 "8 7 2 83\n"61 "1 2 3 94\n"62 "5 7 4 35\n"63 "7 4 5 84\n"64 "9 5 6 38\n"65 "0 4 7 96\n"66 "6 7 8 6\n"67 "3 1 9 27\n"68 "5 2 10 77\n"69 "5 6 11 69\n"70 "6 5 12 41\n"71 "4 6 13 70\n"72 "3 2 14 45\n"73 "7 9 15 93\n"74 "5 9 16 50\n"75 "9 0 17 94\n"76 "9 6 18 67\n"77 "0 9 19 86\n"78 "@attributes\n" 43 char test_lgf[] = 44 "@nodes\n" 45 "label\n" 46 "0\n" 47 "1\n" 48 "2\n" 49 "3\n" 50 "4\n" 51 "5\n" 52 "6\n" 53 "7\n" 54 "8\n" 55 "9\n" 56 "@arcs\n" 57 " label capacity\n" 58 "0 5 0 94\n" 59 "3 9 1 11\n" 60 "8 7 2 83\n" 61 "1 2 3 94\n" 62 "5 7 4 35\n" 63 "7 4 5 84\n" 64 "9 5 6 38\n" 65 "0 4 7 96\n" 66 "6 7 8 6\n" 67 "3 1 9 27\n" 68 "5 2 10 77\n" 69 "5 6 11 69\n" 70 "6 5 12 41\n" 71 "4 6 13 70\n" 72 "3 2 14 45\n" 73 "7 9 15 93\n" 74 "5 9 16 50\n" 75 "9 0 17 94\n" 76 "9 6 18 67\n" 77 "0 9 19 86\n" 78 "@attributes\n" 79 79 "source 3\n"; 80 80 … … 89 89 90 90 Heap heap(map); 91 91 92 92 std::vector<int> v(test_len); 93 93 … … 108 108 109 109 Heap heap(map); 110 110 111 111 std::vector<int> v(test_len); 112 112 … … 129 129 130 130 template <typename Heap> 131 void dijkstraHeapTest(const Digraph& digraph, const IntArcMap& length, 132 133 131 void dijkstraHeapTest(const Digraph& digraph, const IntArcMap& length, 132 Node source) { 133 134 134 typename Dijkstra<Digraph, IntArcMap>::template DefStandardHeap<Heap>:: 135 135 Create dijkstra(digraph, length); … … 138 138 139 139 for(ArcIt a(digraph); a != INVALID; ++a) { 140 Node s = digraph.source(a); 140 Node s = digraph.source(a); 141 141 Node t = digraph.target(a); 142 142 if (dijkstra.reached(s)) { 143 143 check( dijkstra.dist(t) - dijkstra.dist(s) <= length[a], 144 144 "Error in a shortest path tree!"); 145 145 } 146 146 } … … 151 151 Node s = digraph.source(a); 152 152 check( dijkstra.dist(n) - dijkstra.dist(s) == length[a], 153 153 "Error in a shortest path tree!"); 154 154 } 155 155 } … … 162 162 typedef int Prio; 163 163 typedef RangeMap<int> ItemIntMap; 164 164 165 165 Digraph digraph; 166 166 IntArcMap length(digraph); … … 171 171 arcMap("capacity", length). 172 172 node("source", source). 173 run(); 174 173 run(); 174 175 175 { 176 176 typedef BinHeap<Prio, ItemIntMap> IntHeap; … … 178 178 heapSortTest<IntHeap>(); 179 179 heapIncreaseTest<IntHeap>(); 180 180 181 181 typedef BinHeap<Prio, IntNodeMap > NodeHeap; 182 182 checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>(); -
test/kruskal_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 74 74 Node v4=G.addNode(); 75 75 Node t=G.addNode(); 76 76 77 77 Edge e1 = G.addEdge(s, v1); 78 78 Edge e2 = G.addEdge(s, v2); … … 91 91 ECostMap edge_cost_map(G, 2); 92 92 EBoolMap tree_map(G); 93 93 94 94 95 95 //Test with const map. 96 96 check(kruskal(G, ConstMap<ListGraph::Edge,int>(2), tree_map)==10, 97 97 "Total cost should be 10"); 98 98 //Test with an edge map (filled with uniform costs). 99 99 check(kruskal(G, edge_cost_map, tree_map)==10, 100 100 "Total cost should be 10"); 101 101 102 102 edge_cost_map.set(e1, -10); … … 115 115 //Test with a edge map and inserter. 116 116 check(kruskal(G, edge_cost_map, 117 118 119 120 117 tree_edge_vec.begin()) 118 ==-31, 119 "Total cost should be -31."); 120 121 121 tree_edge_vec.clear(); 122 122 123 123 check(kruskal(G, edge_cost_map, 124 125 126 127 124 back_inserter(tree_edge_vec)) 125 ==-31, 126 "Total cost should be -31."); 127 128 128 // tree_edge_vec.clear(); 129 129 130 130 // //The above test could also be coded like this: 131 131 // check(kruskal(G, 132 // 133 // 134 // 135 // 132 // makeKruskalMapInput(G, edge_cost_map), 133 // makeKruskalSequenceOutput(back_inserter(tree_edge_vec))) 134 // ==-31, 135 // "Total cost should be -31."); 136 136 137 137 check(tree_edge_vec.size()==5,"The tree should have 5 edges."); 138 138 139 139 check(tree_edge_vec[0]==e1 && 140 141 142 143 144 140 tree_edge_vec[1]==e2 && 141 tree_edge_vec[2]==e5 && 142 tree_edge_vec[3]==e7 && 143 tree_edge_vec[4]==e9, 144 "Wrong tree."); 145 145 146 146 return 0; -
test/maps_test.cc
r167 r209 1 /* -*- C++-*-2 * 3 * This file is a part of LEMON, a generic C++ optimization library 1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 * 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 305 305 "Something is wrong with EqualMap"); 306 306 } 307 307 308 308 // LoggerBoolMap 309 309 { … … 321 321 v1[0]==20 && v1[1]==50 && v1[2]==60 && v2[0]==20 && v2[1]==50 && v2[2]==60, 322 322 "Something is wrong with LoggerBoolMap"); 323 323 324 324 int i = 0; 325 325 for ( LoggerBoolMap<vec::iterator>::Iterator it = map2.begin(); -
test/path_test.cc
r96 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 40 40 41 41 int main() { 42 check_concepts(); 42 check_concepts(); 43 43 return 0; 44 44 } -
test/random_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 34 34 35 35 lemon::rnd.seed(100); 36 lemon::rnd.seed(seed_array, seed_array + 37 36 lemon::rnd.seed(seed_array, seed_array + 37 (sizeof(seed_array) / sizeof(seed_array[0]))); 38 38 39 39 return 0; -
test/test_tools.h
r184 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 -
test/test_tools_fail.cc
r39 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 19 19 #include "test_tools.h" 20 20 21 int main() 21 int main() 22 22 { 23 23 check(false, "Don't panic. Failing is the right behaviour here."); -
test/test_tools_pass.cc
r39 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 19 19 #include "test_tools.h" 20 20 21 int main() 21 int main() 22 22 { 23 23 check(true, "It should pass."); -
test/time_measure_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 21 21 using namespace lemon; 22 22 23 void f() 23 void f() 24 24 { 25 25 double d=0; … … 28 28 } 29 29 30 void g() 30 void g() 31 31 { 32 32 static Timer T; 33 33 34 34 for(int i=0;i<1000;i++) 35 35 TimeStamp x(T); … … 50 50 std::cout << t << " (" << n << " tests)\n"; 51 51 std::cout << "Total: " << full << "\n"; 52 52 53 53 t=runningTimeTest(g,1,&n,&full); 54 54 std::cout << t << " (" << n << " tests)\n"; 55 55 std::cout << "Total: " << full << "\n"; 56 56 57 57 return 0; 58 58 } -
test/unionfind_test.cc
r171 r209 1 /* -*- C++-*-1 /* -*- mode: C++; indent-tabs-mode: nil; -*- 2 2 * 3 * This file is a part of LEMON, a generic C++ optimization library 3 * This file is a part of LEMON, a generic C++ optimization library. 4 4 * 5 5 * Copyright (C) 2003-2008 … … 32 32 UFE U(base); 33 33 vector<ListGraph::Node> n; 34 34 35 35 for(int i=0;i<20;i++) n.push_back(g.addNode()); 36 36
Note: See TracChangeset
for help on using the changeset viewer.