gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 15 0
merge default
0 files changed:
↑ Collapse diff ↑
Ignore white space 6144 line context
1 1
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
2 2

	
3 3
IF(EXISTS ${CMAKE_SOURCE_DIR}/cmake/version.cmake)
4 4
  INCLUDE(${CMAKE_SOURCE_DIR}/cmake/version.cmake)
5 5
ELSE(EXISTS ${CMAKE_SOURCE_DIR}/cmake/version.cmake)
6 6
  SET(PROJECT_NAME "LEMON")
7 7
  SET(PROJECT_VERSION "hg-tip" CACHE STRING "LEMON version string.")
8 8
ENDIF(EXISTS ${CMAKE_SOURCE_DIR}/cmake/version.cmake)
9 9

	
10 10
PROJECT(${PROJECT_NAME})
11 11

	
12 12
SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
13 13

	
14 14
INCLUDE(FindDoxygen)
15 15
INCLUDE(FindGhostscript)
16 16
FIND_PACKAGE(GLPK 4.33)
17 17
FIND_PACKAGE(CPLEX)
18 18
FIND_PACKAGE(COIN)
19 19

	
20
ADD_DEFINITIONS(-DHAVE_CONFIG_H)
21

	
22 20
IF(MSVC)
23 21
  SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4250 /wd4355 /wd4800 /wd4996")
24 22
# Suppressed warnings:
25 23
# C4250: 'class1' : inherits 'class2::member' via dominance
26 24
# C4355: 'this' : used in base member initializer list
27 25
# C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
28 26
# C4996: 'function': was declared deprecated
29 27
ENDIF(MSVC)
30 28

	
31
ADD_DEFINITIONS(-DHAVE_CONFIG_H)
32

	
33 29
INCLUDE(CheckTypeSize)
34 30
CHECK_TYPE_SIZE("long long" LEMON_LONG_LONG)
35 31

	
36 32
ENABLE_TESTING()
37 33

	
38 34
ADD_SUBDIRECTORY(lemon)
39 35
IF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
40 36
  ADD_SUBDIRECTORY(demo)
41 37
  ADD_SUBDIRECTORY(tools)
42 38
  ADD_SUBDIRECTORY(doc)
43 39
  ADD_SUBDIRECTORY(test)
44 40
ENDIF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
45 41

	
46 42
IF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
47 43
  IF(WIN32)
48 44
    SET(CPACK_PACKAGE_NAME ${PROJECT_NAME})
49 45
    SET(CPACK_PACKAGE_VENDOR "EGRES")
50 46
    SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY
51 47
      "LEMON - Library of Efficient Models and Optimization in Networks")
52 48
    SET(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE")
53 49

	
54 50
    SET(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
55 51

	
56 52
    SET(CPACK_PACKAGE_INSTALL_DIRECTORY
57 53
      "${PROJECT_NAME} ${PROJECT_VERSION}")
58 54
    SET(CPACK_PACKAGE_INSTALL_REGISTRY_KEY
59 55
      "${PROJECT_NAME} ${PROJECT_VERSION}")
60 56

	
61 57
    SET(CPACK_COMPONENTS_ALL headers library html_documentation bin)
62 58

	
63 59
    SET(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "C++ headers")
64 60
    SET(CPACK_COMPONENT_LIBRARY_DISPLAY_NAME "Dynamic-link library")
65 61
    SET(CPACK_COMPONENT_BIN_DISPLAY_NAME "Command line utilities")
66 62
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_DISPLAY_NAME "HTML documentation")
67 63

	
68 64
    SET(CPACK_COMPONENT_HEADERS_DESCRIPTION
69 65
      "C++ header files")
70 66
    SET(CPACK_COMPONENT_LIBRARY_DESCRIPTION
71 67
      "DLL and import library")
72 68
    SET(CPACK_COMPONENT_BIN_DESCRIPTION
73 69
      "Command line utilities")
74 70
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_DESCRIPTION
75 71
      "Doxygen generated documentation")
76 72

	
77 73
    SET(CPACK_COMPONENT_HEADERS_DEPENDS library)
78 74

	
79 75
    SET(CPACK_COMPONENT_HEADERS_GROUP "Development")
80 76
    SET(CPACK_COMPONENT_LIBRARY_GROUP "Development")
81 77
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_GROUP "Documentation")
82 78

	
83 79
    SET(CPACK_COMPONENT_GROUP_DEVELOPMENT_DESCRIPTION
84 80
      "Components needed to develop software using LEMON")
85 81
    SET(CPACK_COMPONENT_GROUP_DOCUMENTATION_DESCRIPTION
86 82
      "Documentation of LEMON")
87 83

	
88 84
    SET(CPACK_ALL_INSTALL_TYPES Full Developer)
89 85

	
90 86
    SET(CPACK_COMPONENT_HEADERS_INSTALL_TYPES Developer Full)
91 87
    SET(CPACK_COMPONENT_LIBRARY_INSTALL_TYPES Developer Full)
92 88
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_INSTALL_TYPES Full)
93 89

	
94 90
    SET(CPACK_GENERATOR "NSIS")
95 91
    SET(CPACK_NSIS_MUI_ICON "${PROJECT_SOURCE_DIR}/cmake/nsis/lemon.ico")
96 92
    SET(CPACK_NSIS_MUI_UNIICON "${PROJECT_SOURCE_DIR}/cmake/nsis/uninstall.ico")
97 93
    #SET(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/cmake/nsis\\\\installer.bmp")
98 94
    SET(CPACK_NSIS_INSTALLED_ICON_NAME "bin\\\\lemon.ico")
99 95
    SET(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY} ${PROJECT_NAME}")
100 96
    SET(CPACK_NSIS_HELP_LINK "http:\\\\\\\\lemon.cs.elte.hu")
101 97
    SET(CPACK_NSIS_URL_INFO_ABOUT "http:\\\\\\\\lemon.cs.elte.hu")
102 98
    SET(CPACK_NSIS_CONTACT "lemon-user@lemon.cs.elte.hu")
103 99
    SET(CPACK_NSIS_CREATE_ICONS_EXTRA "
104 100
      CreateShortCut \\\"$SMPROGRAMS\\\\$STARTMENU_FOLDER\\\\Documentation.lnk\\\" \\\"$INSTDIR\\\\share\\\\doc\\\\index.html\\\"
105 101
      ")
106 102
    SET(CPACK_NSIS_DELETE_ICONS_EXTRA "
107 103
      !insertmacro MUI_STARTMENU_GETFOLDER Application $MUI_TEMP
108 104
      Delete \\\"$SMPROGRAMS\\\\$MUI_TEMP\\\\Documentation.lnk\\\"
109 105
      ")
110 106

	
111 107
    INCLUDE(CPack)
112 108
  ENDIF(WIN32)
113 109
ENDIF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
Ignore white space 6 line context
1 1
ACLOCAL_AMFLAGS = -I m4
2 2

	
3 3
AM_CXXFLAGS = $(WARNINGCXXFLAGS)
4 4

	
5 5
AM_CPPFLAGS = -I$(top_srcdir) -I$(top_builddir)
6 6
LDADD = $(top_builddir)/lemon/libemon.la
7 7

	
8 8
EXTRA_DIST = \
9 9
	AUTHORS \
10 10
	LICENSE \
11 11
	m4/lx_check_cplex.m4 \
12 12
	m4/lx_check_glpk.m4 \
13 13
	m4/lx_check_soplex.m4 \
14
	m4/lx_check_clp.m4 \
15
	m4/lx_check_cbc.m4 \
14
	m4/lx_check_coin.m4 \
16 15
	CMakeLists.txt \
17 16
	cmake/FindGhostscript.cmake \
17
	cmake/FindCPLEX.cmake \
18 18
	cmake/FindGLPK.cmake \
19
	cmake/FindCOIN.cmake \
19 20
	cmake/version.cmake.in \
20 21
	cmake/version.cmake \
21 22
	cmake/nsis/lemon.ico \
22 23
	cmake/nsis/uninstall.ico
23 24

	
24 25
pkgconfigdir = $(libdir)/pkgconfig
25 26
lemondir = $(pkgincludedir)
26 27
bitsdir = $(lemondir)/bits
27 28
conceptdir = $(lemondir)/concepts
28 29
pkgconfig_DATA =
29 30
lib_LTLIBRARIES =
30 31
lemon_HEADERS =
31 32
bits_HEADERS =
32 33
concept_HEADERS =
33 34
noinst_HEADERS =
34 35
noinst_PROGRAMS =
35 36
bin_PROGRAMS =
36 37
check_PROGRAMS =
37 38
dist_bin_SCRIPTS =
38 39
TESTS =
39 40
XFAIL_TESTS =
40 41

	
41 42
include lemon/Makefile.am
42 43
include test/Makefile.am
43 44
include doc/Makefile.am
44 45
include tools/Makefile.am
45 46

	
46 47
DIST_SUBDIRS = demo
47 48

	
48 49
demo:
49 50
	$(MAKE) $(AM_MAKEFLAGS) -C demo
50 51

	
51 52
MRPROPERFILES = \
52 53
	aclocal.m4 \
53 54
	config.h.in \
54 55
	config.h.in~ \
55 56
	configure \
56 57
	Makefile.in \
57 58
	build-aux/config.guess \
58 59
	build-aux/config.sub \
59 60
	build-aux/depcomp \
60 61
	build-aux/install-sh \
61 62
	build-aux/ltmain.sh \
62 63
	build-aux/missing \
63 64
	doc/doxygen.log
64 65

	
65 66
mrproper:
66 67
	$(MAKE) $(AM_MAKEFLAGS) maintainer-clean
67 68
	-rm -f $(MRPROPERFILES)
68 69

	
69 70
dist-bz2: dist
70 71
	zcat $(PACKAGE)-$(VERSION).tar.gz | \
71 72
	bzip2 --best -c > $(PACKAGE)-$(VERSION).tar.bz2
72 73

	
73 74
distcheck-bz2: distcheck
74 75
	zcat $(PACKAGE)-$(VERSION).tar.gz | \
75 76
	bzip2 --best -c > $(PACKAGE)-$(VERSION).tar.bz2
76 77

	
77 78
.PHONY: demo mrproper dist-bz2 distcheck-bz2
Ignore white space 6 line context
1 1
SET(COIN_ROOT_DIR "" CACHE PATH "COIN root directory")
2 2

	
3 3
FIND_PATH(COIN_INCLUDE_DIR coin/CoinUtilsConfig.h
4
  PATHS ${COIN_ROOT_DIR}/include)
5

	
6
FIND_LIBRARY(COIN_CBC_LIBRARY libCbc
7
  PATHS ${COIN_ROOT_DIR}/lib)
8
FIND_LIBRARY(COIN_CBC_SOLVER_LIBRARY libCbcSolver
9
  PATHS ${COIN_ROOT_DIR}/lib)
10
FIND_LIBRARY(COIN_CGL_LIBRARY libCgl
11
  PATHS ${COIN_ROOT_DIR}/lib)
12
FIND_LIBRARY(COIN_CLP_LIBRARY libClp
13
  PATHS ${COIN_ROOT_DIR}/lib)
14
FIND_LIBRARY(COIN_COIN_UTILS_LIBRARY libCoinUtils
15
  PATHS ${COIN_ROOT_DIR}/lib)
16
FIND_LIBRARY(COIN_OSI_LIBRARY libOsi
17
  PATHS ${COIN_ROOT_DIR}/lib)
18
FIND_LIBRARY(COIN_OSI_CBC_LIBRARY libOsiCbc
19
  PATHS ${COIN_ROOT_DIR}/lib)
20
FIND_LIBRARY(COIN_OSI_CLP_LIBRARY libOsiClp
21
  PATHS ${COIN_ROOT_DIR}/lib)
22
FIND_LIBRARY(COIN_OSI_VOL_LIBRARY libOsiVol
23
  PATHS ${COIN_ROOT_DIR}/lib)
24
FIND_LIBRARY(COIN_VOL_LIBRARY libVol
25
  PATHS ${COIN_ROOT_DIR}/lib)
4
  HINTS ${COIN_ROOT_DIR}/include
5
)
6
FIND_LIBRARY(COIN_CBC_LIBRARY
7
  NAMES Cbc libCbc
8
  HINTS ${COIN_ROOT_DIR}/lib
9
)
10
FIND_LIBRARY(COIN_CBC_SOLVER_LIBRARY
11
  NAMES CbcSolver libCbcSolver
12
  HINTS ${COIN_ROOT_DIR}/lib
13
)
14
FIND_LIBRARY(COIN_CGL_LIBRARY
15
  NAMES Cgl libCgl
16
  HINTS ${COIN_ROOT_DIR}/lib
17
)
18
FIND_LIBRARY(COIN_CLP_LIBRARY
19
  NAMES Clp libClp
20
  HINTS ${COIN_ROOT_DIR}/lib
21
)
22
FIND_LIBRARY(COIN_COIN_UTILS_LIBRARY
23
  NAMES CoinUtils libCoinUtils
24
  HINTS ${COIN_ROOT_DIR}/lib
25
)
26
FIND_LIBRARY(COIN_OSI_LIBRARY
27
  NAMES Osi libOsi
28
  HINTS ${COIN_ROOT_DIR}/lib
29
)
30
FIND_LIBRARY(COIN_OSI_CBC_LIBRARY
31
  NAMES OsiCbc libOsiCbc
32
  HINTS ${COIN_ROOT_DIR}/lib
33
)
34
FIND_LIBRARY(COIN_OSI_CLP_LIBRARY
35
  NAMES OsiClp libOsiClp
36
  HINTS ${COIN_ROOT_DIR}/lib
37
)
38
FIND_LIBRARY(COIN_OSI_VOL_LIBRARY
39
  NAMES OsiVol libOsiVol
40
  HINTS ${COIN_ROOT_DIR}/lib
41
)
42
FIND_LIBRARY(COIN_VOL_LIBRARY
43
  NAMES Vol libVol
44
  HINTS ${COIN_ROOT_DIR}/lib
45
)
26 46

	
27 47
INCLUDE(FindPackageHandleStandardArgs)
28 48
FIND_PACKAGE_HANDLE_STANDARD_ARGS(COIN DEFAULT_MSG
29 49
  COIN_INCLUDE_DIR
30 50
  COIN_CBC_LIBRARY
31 51
  COIN_CBC_SOLVER_LIBRARY
32 52
  COIN_CGL_LIBRARY
33 53
  COIN_CLP_LIBRARY
34 54
  COIN_COIN_UTILS_LIBRARY
35 55
  COIN_OSI_LIBRARY
36 56
  COIN_OSI_CBC_LIBRARY
37 57
  COIN_OSI_CLP_LIBRARY
38 58
  COIN_OSI_VOL_LIBRARY
39 59
  COIN_VOL_LIBRARY
40 60
)
41 61

	
42 62
IF(COIN_FOUND)
43 63
  SET(COIN_INCLUDE_DIRS ${COIN_INCLUDE_DIR})
44 64
  SET(COIN_LIBRARIES "${COIN_CBC_LIBRARY};${COIN_CBC_SOLVER_LIBRARY};${COIN_CGL_LIBRARY};${COIN_CLP_LIBRARY};${COIN_COIN_UTILS_LIBRARY};${COIN_OSI_LIBRARY};${COIN_OSI_CBC_LIBRARY};${COIN_OSI_CLP_LIBRARY};${COIN_OSI_VOL_LIBRARY};${COIN_VOL_LIBRARY}")
45 65
  SET(COIN_CLP_LIBRARIES "${COIN_CLP_LIBRARY};${COIN_COIN_UTILS_LIBRARY}")
46 66
  SET(COIN_CBC_LIBRARIES ${COIN_LIBRARIES})
47 67
ENDIF(COIN_FOUND)
48 68

	
49 69
MARK_AS_ADVANCED(
50 70
  COIN_INCLUDE_DIR
51 71
  COIN_CBC_LIBRARY
52 72
  COIN_CBC_SOLVER_LIBRARY
53 73
  COIN_CGL_LIBRARY
54 74
  COIN_CLP_LIBRARY
55 75
  COIN_COIN_UTILS_LIBRARY
56 76
  COIN_OSI_LIBRARY
57 77
  COIN_OSI_CBC_LIBRARY
58 78
  COIN_OSI_CLP_LIBRARY
59 79
  COIN_OSI_VOL_LIBRARY
60 80
  COIN_VOL_LIBRARY
61 81
)
62 82

	
63 83
IF(COIN_FOUND)
64 84
  SET(LEMON_HAVE_LP TRUE)
65 85
  SET(LEMON_HAVE_MIP TRUE)
66 86
  SET(LEMON_HAVE_CLP TRUE)
67 87
  SET(LEMON_HAVE_CBC TRUE)
68 88
ENDIF(COIN_FOUND)
Ignore white space 6 line context
1
SET(CPLEX_ROOT_DIR "" CACHE PATH "CPLEX root directory")
2

	
1 3
FIND_PATH(CPLEX_INCLUDE_DIR
2 4
  ilcplex/cplex.h
3
  PATHS "C:/ILOG/CPLEX91/include")
4

	
5
  PATHS "C:/ILOG/CPLEX91/include"
6
  PATHS "/opt/ilog/cplex91/include"
7
  HINTS ${CPLEX_ROOT_DIR}/include
8
)
5 9
FIND_LIBRARY(CPLEX_LIBRARY
6
  NAMES cplex91
7
  PATHS "C:/ILOG/CPLEX91/lib/msvc7/stat_mda")
10
  cplex91
11
  PATHS "C:/ILOG/CPLEX91/lib/msvc7/stat_mda"
12
  PATHS "/opt/ilog/cplex91/bin"
13
  HINTS ${CPLEX_ROOT_DIR}/bin
14
)
8 15

	
9 16
INCLUDE(FindPackageHandleStandardArgs)
10 17
FIND_PACKAGE_HANDLE_STANDARD_ARGS(CPLEX DEFAULT_MSG CPLEX_LIBRARY CPLEX_INCLUDE_DIR)
11 18

	
12 19
FIND_PATH(CPLEX_BIN_DIR
13 20
  cplex91.dll
14
  PATHS "C:/ILOG/CPLEX91/bin/x86_win32")
21
  PATHS "C:/ILOG/CPLEX91/bin/x86_win32"
22
)
15 23

	
16 24
IF(CPLEX_FOUND)
17 25
  SET(CPLEX_INCLUDE_DIRS ${CPLEX_INCLUDE_DIR})
18 26
  SET(CPLEX_LIBRARIES ${CPLEX_LIBRARY})
27
  IF(CMAKE_SYSTEM_NAME STREQUAL "Linux")
28
    SET(CPLEX_LIBRARIES "${CPLEX_LIBRARIES};m;pthread")
29
  ENDIF(CMAKE_SYSTEM_NAME STREQUAL "Linux")
19 30
ENDIF(CPLEX_FOUND)
20 31

	
21 32
MARK_AS_ADVANCED(CPLEX_LIBRARY CPLEX_INCLUDE_DIR CPLEX_BIN_DIR)
22 33

	
23 34
IF(CPLEX_FOUND)
24 35
  SET(LEMON_HAVE_LP TRUE)
25 36
  SET(LEMON_HAVE_MIP TRUE)
26 37
  SET(LEMON_HAVE_CPLEX TRUE)
27 38
ENDIF(CPLEX_FOUND)
Ignore white space 6 line context
1
SET(GLPK_ROOT_DIR "" CACHE PATH "GLPK root directory")
2

	
1 3
SET(GLPK_REGKEY "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\Glpk;InstallPath]")
2 4
GET_FILENAME_COMPONENT(GLPK_ROOT_PATH ${GLPK_REGKEY} ABSOLUTE)
3 5

	
4 6
FIND_PATH(GLPK_INCLUDE_DIR
5 7
  glpk.h
6
  PATHS ${GLPK_REGKEY}/include)
8
  PATHS ${GLPK_REGKEY}/include
9
  HINTS ${GLPK_ROOT_DIR}/include
10
)
11
FIND_LIBRARY(GLPK_LIBRARY
12
  glpk
13
  PATHS ${GLPK_REGKEY}/lib
14
  HINTS ${GLPK_ROOT_DIR}/lib
15
)
7 16

	
8
FIND_LIBRARY(GLPK_LIBRARY
9
  NAMES glpk
10
  PATHS ${GLPK_REGKEY}/lib)
17
IF(GLPK_INCLUDE_DIR AND GLPK_LIBRARY)
18
  FILE(READ ${GLPK_INCLUDE_DIR}/glpk.h GLPK_GLPK_H)
19

	
20
  STRING(REGEX MATCH "define[ ]+GLP_MAJOR_VERSION[ ]+[0-9]+" GLPK_MAJOR_VERSION_LINE "${GLPK_GLPK_H}")
21
  STRING(REGEX REPLACE "define[ ]+GLP_MAJOR_VERSION[ ]+([0-9]+)" "\\1" GLPK_VERSION_MAJOR "${GLPK_MAJOR_VERSION_LINE}")
22

	
23
  STRING(REGEX MATCH "define[ ]+GLP_MINOR_VERSION[ ]+[0-9]+" GLPK_MINOR_VERSION_LINE "${GLPK_GLPK_H}")
24
  STRING(REGEX REPLACE "define[ ]+GLP_MINOR_VERSION[ ]+([0-9]+)" "\\1" GLPK_VERSION_MINOR "${GLPK_MINOR_VERSION_LINE}")
25

	
26
  SET(GLPK_VERSION_STRING "${GLPK_VERSION_MAJOR}.${GLPK_VERSION_MINOR}")
27

	
28
  IF(GLPK_FIND_VERSION)
29
    IF(GLPK_FIND_VERSION_COUNT GREATER 2)
30
      MESSAGE(SEND_ERROR "unexpected version string")
31
    ENDIF(GLPK_FIND_VERSION_COUNT GREATER 2)
32

	
33
    MATH(EXPR GLPK_REQUESTED_VERSION "${GLPK_FIND_VERSION_MAJOR}*100 + ${GLPK_FIND_VERSION_MINOR}")
34
    MATH(EXPR GLPK_FOUND_VERSION "${GLPK_VERSION_MAJOR}*100 + ${GLPK_VERSION_MINOR}")
35

	
36
    IF(GLPK_FOUND_VERSION LESS GLPK_REQUESTED_VERSION)
37
      SET(GLPK_PROPER_VERSION_FOUND FALSE)
38
    ELSE(GLPK_FOUND_VERSION LESS GLPK_REQUESTED_VERSION)
39
      SET(GLPK_PROPER_VERSION_FOUND TRUE)
40
    ENDIF(GLPK_FOUND_VERSION LESS GLPK_REQUESTED_VERSION)
41
  ELSE(GLPK_FIND_VERSION)
42
    SET(GLPK_PROPER_VERSION_FOUND TRUE)
43
  ENDIF(GLPK_FIND_VERSION)
44
ENDIF(GLPK_INCLUDE_DIR AND GLPK_LIBRARY)
11 45

	
12 46
INCLUDE(FindPackageHandleStandardArgs)
13
FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLPK DEFAULT_MSG GLPK_LIBRARY GLPK_INCLUDE_DIR)
47
FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLPK DEFAULT_MSG GLPK_LIBRARY GLPK_INCLUDE_DIR GLPK_PROPER_VERSION_FOUND)
14 48

	
15 49
IF(GLPK_FOUND)
16 50
  SET(GLPK_INCLUDE_DIRS ${GLPK_INCLUDE_DIR})
17 51
  SET(GLPK_LIBRARIES ${GLPK_LIBRARY})
18 52
  SET(GLPK_BIN_DIR ${GLPK_ROOT_PATH}/bin)
19 53
ENDIF(GLPK_FOUND)
20 54

	
21 55
MARK_AS_ADVANCED(GLPK_LIBRARY GLPK_INCLUDE_DIR GLPK_BIN_DIR)
22 56

	
23 57
IF(GLPK_FOUND)
24 58
  SET(LEMON_HAVE_LP TRUE)
25 59
  SET(LEMON_HAVE_MIP TRUE)
26 60
  SET(LEMON_HAVE_GLPK TRUE)
27 61
ENDIF(GLPK_FOUND)
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
namespace lemon {
20 20

	
21 21
/**
22 22
@defgroup datas Data Structures
23 23
This group contains the several data structures implemented in LEMON.
24 24
*/
25 25

	
26 26
/**
27 27
@defgroup graphs Graph Structures
28 28
@ingroup datas
29 29
\brief Graph structures implemented in LEMON.
30 30

	
31 31
The implementation of combinatorial algorithms heavily relies on
32 32
efficient graph implementations. LEMON offers data structures which are
33 33
planned to be easily used in an experimental phase of implementation studies,
34 34
and thereafter the program code can be made efficient by small modifications.
35 35

	
36 36
The most efficient implementation of diverse applications require the
37 37
usage of different physical graph implementations. These differences
38 38
appear in the size of graph we require to handle, memory or time usage
39 39
limitations or in the set of operations through which the graph can be
40 40
accessed.  LEMON provides several physical graph structures to meet
41 41
the diverging requirements of the possible users.  In order to save on
42 42
running time or on memory usage, some structures may fail to provide
43 43
some graph features like arc/edge or node deletion.
44 44

	
45 45
Alteration of standard containers need a very limited number of
46 46
operations, these together satisfy the everyday requirements.
47 47
In the case of graph structures, different operations are needed which do
48 48
not alter the physical graph, but gives another view. If some nodes or
49 49
arcs have to be hidden or the reverse oriented graph have to be used, then
50 50
this is the case. It also may happen that in a flow implementation
51 51
the residual graph can be accessed by another algorithm, or a node-set
52 52
is to be shrunk for another algorithm.
53 53
LEMON also provides a variety of graphs for these requirements called
54 54
\ref graph_adaptors "graph adaptors". Adaptors cannot be used alone but only
55 55
in conjunction with other graph representations.
56 56

	
57 57
You are free to use the graph structure that fit your requirements
58 58
the best, most graph algorithms and auxiliary data structures can be used
59 59
with any graph structure.
60 60

	
61 61
<b>See also:</b> \ref graph_concepts "Graph Structure Concepts".
62 62
*/
63 63

	
64 64
/**
65 65
@defgroup graph_adaptors Adaptor Classes for Graphs
66 66
@ingroup graphs
67 67
\brief Adaptor classes for digraphs and graphs
68 68

	
69 69
This group contains several useful adaptor classes for digraphs and graphs.
70 70

	
71 71
The main parts of LEMON are the different graph structures, generic
72 72
graph algorithms, graph concepts, which couple them, and graph
73 73
adaptors. While the previous notions are more or less clear, the
74 74
latter one needs further explanation. Graph adaptors are graph classes
75 75
which serve for considering graph structures in different ways.
76 76

	
77 77
A short example makes this much clearer.  Suppose that we have an
78 78
instance \c g of a directed graph type, say ListDigraph and an algorithm
79 79
\code
80 80
template <typename Digraph>
81 81
int algorithm(const Digraph&);
82 82
\endcode
83 83
is needed to run on the reverse oriented graph.  It may be expensive
84 84
(in time or in memory usage) to copy \c g with the reversed
85 85
arcs.  In this case, an adaptor class is used, which (according
86 86
to LEMON \ref concepts::Digraph "digraph concepts") works as a digraph.
87 87
The adaptor uses the original digraph structure and digraph operations when
88 88
methods of the reversed oriented graph are called.  This means that the adaptor
89 89
have minor memory usage, and do not perform sophisticated algorithmic
90 90
actions.  The purpose of it is to give a tool for the cases when a
91 91
graph have to be used in a specific alteration.  If this alteration is
92 92
obtained by a usual construction like filtering the node or the arc set or
93 93
considering a new orientation, then an adaptor is worthwhile to use.
94 94
To come back to the reverse oriented graph, in this situation
95 95
\code
96 96
template<typename Digraph> class ReverseDigraph;
97 97
\endcode
98 98
template class can be used. The code looks as follows
99 99
\code
100 100
ListDigraph g;
101 101
ReverseDigraph<ListDigraph> rg(g);
102 102
int result = algorithm(rg);
103 103
\endcode
104 104
During running the algorithm, the original digraph \c g is untouched.
105 105
This techniques give rise to an elegant code, and based on stable
106 106
graph adaptors, complex algorithms can be implemented easily.
107 107

	
108 108
In flow, circulation and matching problems, the residual
109 109
graph is of particular importance. Combining an adaptor implementing
110 110
this with shortest path algorithms or minimum mean cycle algorithms,
111 111
a range of weighted and cardinality optimization algorithms can be
112 112
obtained. For other examples, the interested user is referred to the
113 113
detailed documentation of particular adaptors.
114 114

	
115 115
The behavior of graph adaptors can be very different. Some of them keep
116 116
capabilities of the original graph while in other cases this would be
117 117
meaningless. This means that the concepts that they meet depend
118 118
on the graph adaptor, and the wrapped graph.
119 119
For example, if an arc of a reversed digraph is deleted, this is carried
120 120
out by deleting the corresponding arc of the original digraph, thus the
121 121
adaptor modifies the original digraph.
122 122
However in case of a residual digraph, this operation has no sense.
123 123

	
124 124
Let us stand one more example here to simplify your work.
125 125
ReverseDigraph has constructor
126 126
\code
127 127
ReverseDigraph(Digraph& digraph);
128 128
\endcode
129 129
This means that in a situation, when a <tt>const %ListDigraph&</tt>
130 130
reference to a graph is given, then it have to be instantiated with
131 131
<tt>Digraph=const %ListDigraph</tt>.
132 132
\code
133 133
int algorithm1(const ListDigraph& g) {
134 134
  ReverseDigraph<const ListDigraph> rg(g);
135 135
  return algorithm2(rg);
136 136
}
137 137
\endcode
138 138
*/
139 139

	
140 140
/**
141 141
@defgroup semi_adaptors Semi-Adaptor Classes for Graphs
142 142
@ingroup graphs
143 143
\brief Graph types between real graphs and graph adaptors.
144 144

	
145 145
This group contains some graph types between real graphs and graph adaptors.
146 146
These classes wrap graphs to give new functionality as the adaptors do it.
147 147
On the other hand they are not light-weight structures as the adaptors.
148 148
*/
149 149

	
150 150
/**
151 151
@defgroup maps Maps
152 152
@ingroup datas
153 153
\brief Map structures implemented in LEMON.
154 154

	
155 155
This group contains the map structures implemented in LEMON.
156 156

	
157 157
LEMON provides several special purpose maps and map adaptors that e.g. combine
158 158
new maps from existing ones.
159 159

	
160 160
<b>See also:</b> \ref map_concepts "Map Concepts".
161 161
*/
162 162

	
163 163
/**
164 164
@defgroup graph_maps Graph Maps
165 165
@ingroup maps
166 166
\brief Special graph-related maps.
167 167

	
168 168
This group contains maps that are specifically designed to assign
169 169
values to the nodes and arcs/edges of graphs.
170 170

	
171 171
If you are looking for the standard graph maps (\c NodeMap, \c ArcMap,
172 172
\c EdgeMap), see the \ref graph_concepts "Graph Structure Concepts".
173 173
*/
174 174

	
175 175
/**
176 176
\defgroup map_adaptors Map Adaptors
177 177
\ingroup maps
178 178
\brief Tools to create new maps from existing ones
179 179

	
180 180
This group contains map adaptors that are used to create "implicit"
181 181
maps from other maps.
182 182

	
183 183
Most of them are \ref concepts::ReadMap "read-only maps".
184 184
They can make arithmetic and logical operations between one or two maps
185 185
(negation, shifting, addition, multiplication, logical 'and', 'or',
186 186
'not' etc.) or e.g. convert a map to another one of different Value type.
187 187

	
188 188
The typical usage of this classes is passing implicit maps to
189 189
algorithms.  If a function type algorithm is called then the function
190 190
type map adaptors can be used comfortable. For example let's see the
191 191
usage of map adaptors with the \c graphToEps() function.
192 192
\code
193 193
  Color nodeColor(int deg) {
194 194
    if (deg >= 2) {
195 195
      return Color(0.5, 0.0, 0.5);
196 196
    } else if (deg == 1) {
197 197
      return Color(1.0, 0.5, 1.0);
198 198
    } else {
199 199
      return Color(0.0, 0.0, 0.0);
200 200
    }
201 201
  }
202 202

	
203 203
  Digraph::NodeMap<int> degree_map(graph);
204 204

	
205 205
  graphToEps(graph, "graph.eps")
206 206
    .coords(coords).scaleToA4().undirected()
207 207
    .nodeColors(composeMap(functorToMap(nodeColor), degree_map))
208 208
    .run();
209 209
\endcode
210 210
The \c functorToMap() function makes an \c int to \c Color map from the
211 211
\c nodeColor() function. The \c composeMap() compose the \c degree_map
212 212
and the previously created map. The composed map is a proper function to
213 213
get the color of each node.
214 214

	
215 215
The usage with class type algorithms is little bit harder. In this
216 216
case the function type map adaptors can not be used, because the
217 217
function map adaptors give back temporary objects.
218 218
\code
219 219
  Digraph graph;
220 220

	
221 221
  typedef Digraph::ArcMap<double> DoubleArcMap;
222 222
  DoubleArcMap length(graph);
223 223
  DoubleArcMap speed(graph);
224 224

	
225 225
  typedef DivMap<DoubleArcMap, DoubleArcMap> TimeMap;
226 226
  TimeMap time(length, speed);
227 227

	
228 228
  Dijkstra<Digraph, TimeMap> dijkstra(graph, time);
229 229
  dijkstra.run(source, target);
230 230
\endcode
231 231
We have a length map and a maximum speed map on the arcs of a digraph.
232 232
The minimum time to pass the arc can be calculated as the division of
233 233
the two maps which can be done implicitly with the \c DivMap template
234 234
class. We use the implicit minimum time map as the length map of the
235 235
\c Dijkstra algorithm.
236 236
*/
237 237

	
238 238
/**
239 239
@defgroup matrices Matrices
240 240
@ingroup datas
241 241
\brief Two dimensional data storages implemented in LEMON.
242 242

	
243 243
This group contains two dimensional data storages implemented in LEMON.
244 244
*/
245 245

	
246 246
/**
247 247
@defgroup paths Path Structures
248 248
@ingroup datas
249 249
\brief %Path structures implemented in LEMON.
250 250

	
251 251
This group contains the path structures implemented in LEMON.
252 252

	
253 253
LEMON provides flexible data structures to work with paths.
254 254
All of them have similar interfaces and they can be copied easily with
255 255
assignment operators and copy constructors. This makes it easy and
256 256
efficient to have e.g. the Dijkstra algorithm to store its result in
257 257
any kind of path structure.
258 258

	
259 259
\sa lemon::concepts::Path
260 260
*/
261 261

	
262 262
/**
263 263
@defgroup auxdat Auxiliary Data Structures
264 264
@ingroup datas
265 265
\brief Auxiliary data structures implemented in LEMON.
266 266

	
267 267
This group contains some data structures implemented in LEMON in
268 268
order to make it easier to implement combinatorial algorithms.
269 269
*/
270 270

	
271 271
/**
272 272
@defgroup algs Algorithms
273 273
\brief This group contains the several algorithms
274 274
implemented in LEMON.
275 275

	
276 276
This group contains the several algorithms
277 277
implemented in LEMON.
278 278
*/
279 279

	
280 280
/**
281 281
@defgroup search Graph Search
282 282
@ingroup algs
283 283
\brief Common graph search algorithms.
284 284

	
285 285
This group contains the common graph search algorithms, namely
286 286
\e breadth-first \e search (BFS) and \e depth-first \e search (DFS).
287 287
*/
288 288

	
289 289
/**
290 290
@defgroup shortest_path Shortest Path Algorithms
291 291
@ingroup algs
292 292
\brief Algorithms for finding shortest paths.
293 293

	
294 294
This group contains the algorithms for finding shortest paths in digraphs.
295 295

	
296 296
 - \ref Dijkstra algorithm for finding shortest paths from a source node
297 297
   when all arc lengths are non-negative.
298 298
 - \ref BellmanFord "Bellman-Ford" algorithm for finding shortest paths
299 299
   from a source node when arc lenghts can be either positive or negative,
300 300
   but the digraph should not contain directed cycles with negative total
301 301
   length.
302 302
 - \ref FloydWarshall "Floyd-Warshall" and \ref Johnson "Johnson" algorithms
303 303
   for solving the \e all-pairs \e shortest \e paths \e problem when arc
304 304
   lenghts can be either positive or negative, but the digraph should
305 305
   not contain directed cycles with negative total length.
306 306
 - \ref Suurballe A successive shortest path algorithm for finding
307 307
   arc-disjoint paths between two nodes having minimum total length.
308 308
*/
309 309

	
310 310
/**
311 311
@defgroup max_flow Maximum Flow Algorithms
312 312
@ingroup algs
313 313
\brief Algorithms for finding maximum flows.
314 314

	
315 315
This group contains the algorithms for finding maximum flows and
316 316
feasible circulations.
317 317

	
318 318
The \e maximum \e flow \e problem is to find a flow of maximum value between
319 319
a single source and a single target. Formally, there is a \f$G=(V,A)\f$
320 320
digraph, a \f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function and
321 321
\f$s, t \in V\f$ source and target nodes.
322 322
A maximum flow is an \f$f: A\rightarrow\mathbf{R}^+_0\f$ solution of the
323 323
following optimization problem.
324 324

	
325 325
\f[ \max\sum_{sv\in A} f(sv) - \sum_{vs\in A} f(vs) \f]
326 326
\f[ \sum_{uv\in A} f(uv) = \sum_{vu\in A} f(vu)
327 327
    \quad \forall u\in V\setminus\{s,t\} \f]
328 328
\f[ 0 \leq f(uv) \leq cap(uv) \quad \forall uv\in A \f]
329 329

	
330 330
LEMON contains several algorithms for solving maximum flow problems:
331 331
- \ref EdmondsKarp Edmonds-Karp algorithm.
332 332
- \ref Preflow Goldberg-Tarjan's preflow push-relabel algorithm.
333 333
- \ref DinitzSleatorTarjan Dinitz's blocking flow algorithm with dynamic trees.
334 334
- \ref GoldbergTarjan Preflow push-relabel algorithm with dynamic trees.
335 335

	
336 336
In most cases the \ref Preflow "Preflow" algorithm provides the
337 337
fastest method for computing a maximum flow. All implementations
338 338
provides functions to also query the minimum cut, which is the dual
339 339
problem of the maximum flow.
340 340
*/
341 341

	
342 342
/**
343 343
@defgroup min_cost_flow Minimum Cost Flow Algorithms
344 344
@ingroup algs
345 345

	
346 346
\brief Algorithms for finding minimum cost flows and circulations.
347 347

	
348 348
This group contains the algorithms for finding minimum cost flows and
349 349
circulations.
350 350

	
351 351
The \e minimum \e cost \e flow \e problem is to find a feasible flow of
352 352
minimum total cost from a set of supply nodes to a set of demand nodes
353 353
in a network with capacity constraints (lower and upper bounds)
354 354
and arc costs.
355
Formally, let \f$G=(V,A)\f$ be a digraph,
356
\f$lower, upper: A\rightarrow\mathbf{Z}^+_0\f$ denote the lower and
355
Formally, let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{Z}\f$,
356
\f$upper: A\rightarrow\mathbf{Z}\cup\{+\infty\}\f$ denote the lower and
357 357
upper bounds for the flow values on the arcs, for which
358
\f$0 \leq lower(uv) \leq upper(uv)\f$ holds for all \f$uv\in A\f$.
359
\f$cost: A\rightarrow\mathbf{Z}^+_0\f$ denotes the cost per unit flow
360
on the arcs, and \f$sup: V\rightarrow\mathbf{Z}\f$ denotes the
358
\f$lower(uv) \leq upper(uv)\f$ must hold for all \f$uv\in A\f$,
359
\f$cost: A\rightarrow\mathbf{Z}\f$ denotes the cost per unit flow
360
on the arcs and \f$sup: V\rightarrow\mathbf{Z}\f$ denotes the
361 361
signed supply values of the nodes.
362 362
If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
363 363
supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
364 364
\f$-sup(u)\f$ demand.
365
A minimum cost flow is an \f$f: A\rightarrow\mathbf{Z}^+_0\f$ solution
365
A minimum cost flow is an \f$f: A\rightarrow\mathbf{Z}\f$ solution
366 366
of the following optimization problem.
367 367

	
368 368
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
369 369
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
370 370
    sup(u) \quad \forall u\in V \f]
371 371
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
372 372

	
373 373
The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
374 374
zero or negative in order to have a feasible solution (since the sum
375 375
of the expressions on the left-hand side of the inequalities is zero).
376 376
It means that the total demand must be greater or equal to the total
377 377
supply and all the supplies have to be carried out from the supply nodes,
378 378
but there could be demands that are not satisfied.
379 379
If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
380 380
constraints have to be satisfied with equality, i.e. all demands
381 381
have to be satisfied and all supplies have to be used.
382 382

	
383 383
If you need the opposite inequalities in the supply/demand constraints
384 384
(i.e. the total demand is less than the total supply and all the demands
385 385
have to be satisfied while there could be supplies that are not used),
386 386
then you could easily transform the problem to the above form by reversing
387 387
the direction of the arcs and taking the negative of the supply values
388 388
(e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
389 389
However \ref NetworkSimplex algorithm also supports this form directly
390 390
for the sake of convenience.
391 391

	
392 392
A feasible solution for this problem can be found using \ref Circulation.
393 393

	
394 394
Note that the above formulation is actually more general than the usual
395 395
definition of the minimum cost flow problem, in which strict equalities
396 396
are required in the supply/demand contraints, i.e.
397 397

	
398 398
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) =
399 399
    sup(u) \quad \forall u\in V. \f]
400 400

	
401 401
However if the sum of the supply values is zero, then these two problems
402 402
are equivalent. So if you need the equality form, you have to ensure this
403 403
additional contraint for the algorithms.
404 404

	
405 405
The dual solution of the minimum cost flow problem is represented by node 
406 406
potentials \f$\pi: V\rightarrow\mathbf{Z}\f$.
407
An \f$f: A\rightarrow\mathbf{Z}^+_0\f$ feasible solution of the problem
407
An \f$f: A\rightarrow\mathbf{Z}\f$ feasible solution of the problem
408 408
is optimal if and only if for some \f$\pi: V\rightarrow\mathbf{Z}\f$
409 409
node potentials the following \e complementary \e slackness optimality
410 410
conditions hold.
411 411

	
412 412
 - For all \f$uv\in A\f$ arcs:
413 413
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
414 414
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
415 415
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
416
 - For all \f$u\in V\f$:
416
 - For all \f$u\in V\f$ nodes:
417 417
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
418 418
     then \f$\pi(u)=0\f$.
419 419
 
420 420
Here \f$cost^\pi(uv)\f$ denotes the \e reduced \e cost of the arc
421
\f$uv\in A\f$ with respect to the node potentials \f$\pi\f$, i.e.
421
\f$uv\in A\f$ with respect to the potential function \f$\pi\f$, i.e.
422 422
\f[ cost^\pi(uv) = cost(uv) + \pi(u) - \pi(v).\f]
423 423

	
424
All algorithms provide dual solution (node potentials) as well
424
All algorithms provide dual solution (node potentials) as well,
425 425
if an optimal flow is found.
426 426

	
427 427
LEMON contains several algorithms for solving minimum cost flow problems.
428 428
 - \ref NetworkSimplex Primal Network Simplex algorithm with various
429 429
   pivot strategies.
430 430
 - \ref CostScaling Push-Relabel and Augment-Relabel algorithms based on
431 431
   cost scaling.
432 432
 - \ref CapacityScaling Successive Shortest %Path algorithm with optional
433 433
   capacity scaling.
434 434
 - \ref CancelAndTighten The Cancel and Tighten algorithm.
435 435
 - \ref CycleCanceling Cycle-Canceling algorithms.
436 436

	
437 437
Most of these implementations support the general inequality form of the
438 438
minimum cost flow problem, but CancelAndTighten and CycleCanceling
439 439
only support the equality form due to the primal method they use.
440 440

	
441 441
In general NetworkSimplex is the most efficient implementation,
442 442
but in special cases other algorithms could be faster.
443 443
For example, if the total supply and/or capacities are rather small,
444 444
CapacityScaling is usually the fastest algorithm (without effective scaling).
445 445
*/
446 446

	
447 447
/**
448 448
@defgroup min_cut Minimum Cut Algorithms
449 449
@ingroup algs
450 450

	
451 451
\brief Algorithms for finding minimum cut in graphs.
452 452

	
453 453
This group contains the algorithms for finding minimum cut in graphs.
454 454

	
455 455
The \e minimum \e cut \e problem is to find a non-empty and non-complete
456 456
\f$X\f$ subset of the nodes with minimum overall capacity on
457 457
outgoing arcs. Formally, there is a \f$G=(V,A)\f$ digraph, a
458 458
\f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function. The minimum
459 459
cut is the \f$X\f$ solution of the next optimization problem:
460 460

	
461 461
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}
462 462
    \sum_{uv\in A, u\in X, v\not\in X}cap(uv) \f]
463 463

	
464 464
LEMON contains several algorithms related to minimum cut problems:
465 465

	
466 466
- \ref HaoOrlin "Hao-Orlin algorithm" for calculating minimum cut
467 467
  in directed graphs.
468 468
- \ref NagamochiIbaraki "Nagamochi-Ibaraki algorithm" for
469 469
  calculating minimum cut in undirected graphs.
470 470
- \ref GomoryHu "Gomory-Hu tree computation" for calculating
471 471
  all-pairs minimum cut in undirected graphs.
472 472

	
473 473
If you want to find minimum cut just between two distinict nodes,
474 474
see the \ref max_flow "maximum flow problem".
475 475
*/
476 476

	
477 477
/**
478 478
@defgroup graph_properties Connectivity and Other Graph Properties
479 479
@ingroup algs
480 480
\brief Algorithms for discovering the graph properties
481 481

	
482 482
This group contains the algorithms for discovering the graph properties
483 483
like connectivity, bipartiteness, euler property, simplicity etc.
484 484

	
485 485
\image html edge_biconnected_components.png
486 486
\image latex edge_biconnected_components.eps "bi-edge-connected components" width=\textwidth
487 487
*/
488 488

	
489 489
/**
490 490
@defgroup planar Planarity Embedding and Drawing
491 491
@ingroup algs
492 492
\brief Algorithms for planarity checking, embedding and drawing
493 493

	
494 494
This group contains the algorithms for planarity checking,
495 495
embedding and drawing.
496 496

	
497 497
\image html planar.png
498 498
\image latex planar.eps "Plane graph" width=\textwidth
499 499
*/
500 500

	
501 501
/**
502 502
@defgroup matching Matching Algorithms
503 503
@ingroup algs
504 504
\brief Algorithms for finding matchings in graphs and bipartite graphs.
505 505

	
506 506
This group contains the algorithms for calculating
507 507
matchings in graphs and bipartite graphs. The general matching problem is
508 508
finding a subset of the edges for which each node has at most one incident
509 509
edge.
510 510

	
511 511
There are several different algorithms for calculate matchings in
512 512
graphs.  The matching problems in bipartite graphs are generally
513 513
easier than in general graphs. The goal of the matching optimization
514 514
can be finding maximum cardinality, maximum weight or minimum cost
515 515
matching. The search can be constrained to find perfect or
516 516
maximum cardinality matching.
517 517

	
518 518
The matching algorithms implemented in LEMON:
519 519
- \ref MaxBipartiteMatching Hopcroft-Karp augmenting path algorithm
520 520
  for calculating maximum cardinality matching in bipartite graphs.
521 521
- \ref PrBipartiteMatching Push-relabel algorithm
522 522
  for calculating maximum cardinality matching in bipartite graphs.
523 523
- \ref MaxWeightedBipartiteMatching
524 524
  Successive shortest path algorithm for calculating maximum weighted
525 525
  matching and maximum weighted bipartite matching in bipartite graphs.
526 526
- \ref MinCostMaxBipartiteMatching
527 527
  Successive shortest path algorithm for calculating minimum cost maximum
528 528
  matching in bipartite graphs.
529 529
- \ref MaxMatching Edmond's blossom shrinking algorithm for calculating
530 530
  maximum cardinality matching in general graphs.
531 531
- \ref MaxWeightedMatching Edmond's blossom shrinking algorithm for calculating
532 532
  maximum weighted matching in general graphs.
533 533
- \ref MaxWeightedPerfectMatching
534 534
  Edmond's blossom shrinking algorithm for calculating maximum weighted
535 535
  perfect matching in general graphs.
536 536

	
537 537
\image html bipartite_matching.png
538 538
\image latex bipartite_matching.eps "Bipartite Matching" width=\textwidth
539 539
*/
540 540

	
541 541
/**
542 542
@defgroup spantree Minimum Spanning Tree Algorithms
543 543
@ingroup algs
544 544
\brief Algorithms for finding a minimum cost spanning tree in a graph.
545 545

	
546 546
This group contains the algorithms for finding a minimum cost spanning
547 547
tree in a graph.
548 548
*/
549 549

	
550 550
/**
551 551
@defgroup auxalg Auxiliary Algorithms
552 552
@ingroup algs
553 553
\brief Auxiliary algorithms implemented in LEMON.
554 554

	
555 555
This group contains some algorithms implemented in LEMON
556 556
in order to make it easier to implement complex algorithms.
557 557
*/
558 558

	
559 559
/**
560 560
@defgroup approx Approximation Algorithms
561 561
@ingroup algs
562 562
\brief Approximation algorithms.
563 563

	
564 564
This group contains the approximation and heuristic algorithms
565 565
implemented in LEMON.
566 566
*/
567 567

	
568 568
/**
569 569
@defgroup gen_opt_group General Optimization Tools
570 570
\brief This group contains some general optimization frameworks
571 571
implemented in LEMON.
572 572

	
573 573
This group contains some general optimization frameworks
574 574
implemented in LEMON.
575 575
*/
576 576

	
577 577
/**
578 578
@defgroup lp_group Lp and Mip Solvers
579 579
@ingroup gen_opt_group
580 580
\brief Lp and Mip solver interfaces for LEMON.
581 581

	
582 582
This group contains Lp and Mip solver interfaces for LEMON. The
583 583
various LP solvers could be used in the same manner with this
584 584
interface.
585 585
*/
586 586

	
587 587
/**
588 588
@defgroup lp_utils Tools for Lp and Mip Solvers
589 589
@ingroup lp_group
590 590
\brief Helper tools to the Lp and Mip solvers.
591 591

	
592 592
This group adds some helper tools to general optimization framework
593 593
implemented in LEMON.
594 594
*/
595 595

	
596 596
/**
597 597
@defgroup metah Metaheuristics
598 598
@ingroup gen_opt_group
599 599
\brief Metaheuristics for LEMON library.
600 600

	
601 601
This group contains some metaheuristic optimization tools.
602 602
*/
603 603

	
604 604
/**
605 605
@defgroup utils Tools and Utilities
606 606
\brief Tools and utilities for programming in LEMON
607 607

	
608 608
Tools and utilities for programming in LEMON.
609 609
*/
610 610

	
611 611
/**
612 612
@defgroup gutils Basic Graph Utilities
613 613
@ingroup utils
614 614
\brief Simple basic graph utilities.
615 615

	
616 616
This group contains some simple basic graph utilities.
617 617
*/
618 618

	
619 619
/**
620 620
@defgroup misc Miscellaneous Tools
621 621
@ingroup utils
622 622
\brief Tools for development, debugging and testing.
623 623

	
624 624
This group contains several useful tools for development,
625 625
debugging and testing.
626 626
*/
627 627

	
628 628
/**
629 629
@defgroup timecount Time Measuring and Counting
630 630
@ingroup misc
631 631
\brief Simple tools for measuring the performance of algorithms.
632 632

	
633 633
This group contains simple tools for measuring the performance
634 634
of algorithms.
635 635
*/
636 636

	
637 637
/**
638 638
@defgroup exceptions Exceptions
639 639
@ingroup utils
640 640
\brief Exceptions defined in LEMON.
641 641

	
642 642
This group contains the exceptions defined in LEMON.
643 643
*/
644 644

	
645 645
/**
646 646
@defgroup io_group Input-Output
647 647
\brief Graph Input-Output methods
648 648

	
649 649
This group contains the tools for importing and exporting graphs
650 650
and graph related data. Now it supports the \ref lgf-format
651 651
"LEMON Graph Format", the \c DIMACS format and the encapsulated
652 652
postscript (EPS) format.
653 653
*/
654 654

	
655 655
/**
656 656
@defgroup lemon_io LEMON Graph Format
657 657
@ingroup io_group
658 658
\brief Reading and writing LEMON Graph Format.
659 659

	
660 660
This group contains methods for reading and writing
661 661
\ref lgf-format "LEMON Graph Format".
662 662
*/
663 663

	
664 664
/**
665 665
@defgroup eps_io Postscript Exporting
666 666
@ingroup io_group
667 667
\brief General \c EPS drawer and graph exporter
668 668

	
669 669
This group contains general \c EPS drawing methods and special
670 670
graph exporting tools.
671 671
*/
672 672

	
673 673
/**
674 674
@defgroup dimacs_group DIMACS format
675 675
@ingroup io_group
676 676
\brief Read and write files in DIMACS format
677 677

	
678 678
Tools to read a digraph from or write it to a file in DIMACS format data.
679 679
*/
680 680

	
681 681
/**
682 682
@defgroup nauty_group NAUTY Format
683 683
@ingroup io_group
684 684
\brief Read \e Nauty format
685 685

	
686 686
Tool to read graphs from \e Nauty format data.
687 687
*/
688 688

	
689 689
/**
690 690
@defgroup concept Concepts
691 691
\brief Skeleton classes and concept checking classes
692 692

	
693 693
This group contains the data/algorithm skeletons and concept checking
694 694
classes implemented in LEMON.
695 695

	
696 696
The purpose of the classes in this group is fourfold.
697 697

	
698 698
- These classes contain the documentations of the %concepts. In order
699 699
  to avoid document multiplications, an implementation of a concept
700 700
  simply refers to the corresponding concept class.
701 701

	
702 702
- These classes declare every functions, <tt>typedef</tt>s etc. an
703 703
  implementation of the %concepts should provide, however completely
704 704
  without implementations and real data structures behind the
705 705
  interface. On the other hand they should provide nothing else. All
706 706
  the algorithms working on a data structure meeting a certain concept
707 707
  should compile with these classes. (Though it will not run properly,
708 708
  of course.) In this way it is easily to check if an algorithm
709 709
  doesn't use any extra feature of a certain implementation.
710 710

	
711 711
- The concept descriptor classes also provide a <em>checker class</em>
712 712
  that makes it possible to check whether a certain implementation of a
713 713
  concept indeed provides all the required features.
714 714

	
715 715
- Finally, They can serve as a skeleton of a new implementation of a concept.
716 716
*/
717 717

	
718 718
/**
719 719
@defgroup graph_concepts Graph Structure Concepts
720 720
@ingroup concept
721 721
\brief Skeleton and concept checking classes for graph structures
722 722

	
723 723
This group contains the skeletons and concept checking classes of LEMON's
724 724
graph structures and helper classes used to implement these.
725 725
*/
726 726

	
727 727
/**
728 728
@defgroup map_concepts Map Concepts
729 729
@ingroup concept
730 730
\brief Skeleton and concept checking classes for maps
731 731

	
732 732
This group contains the skeletons and concept checking classes of maps.
733 733
*/
734 734

	
735 735
/**
736 736
\anchor demoprograms
737 737

	
738 738
@defgroup demos Demo Programs
739 739

	
740 740
Some demo programs are listed here. Their full source codes can be found in
741 741
the \c demo subdirectory of the source tree.
742 742

	
743 743
In order to compile them, use the <tt>make demo</tt> or the
744 744
<tt>make check</tt> commands.
745 745
*/
746 746

	
747 747
/**
748 748
@defgroup tools Standalone Utility Applications
749 749

	
750 750
Some utility applications are listed here.
751 751

	
752 752
The standard compilation procedure (<tt>./configure;make</tt>) will compile
753 753
them, as well.
754 754
*/
755 755

	
756 756
}
Ignore white space 6 line context
1 1
EXTRA_DIST += \
2 2
	lemon/lemon.pc.in \
3 3
	lemon/CMakeLists.txt
4 4

	
5 5
pkgconfig_DATA += lemon/lemon.pc
6 6

	
7 7
lib_LTLIBRARIES += lemon/libemon.la
8 8

	
9 9
lemon_libemon_la_SOURCES = \
10 10
	lemon/arg_parser.cc \
11 11
	lemon/base.cc \
12 12
	lemon/color.cc \
13 13
	lemon/lp_base.cc \
14 14
	lemon/lp_skeleton.cc \
15 15
	lemon/random.cc \
16 16
	lemon/bits/windows.cc
17 17

	
18

	
18
nodist_lemon_HEADERS = lemon/config.h	
19
	
19 20
lemon_libemon_la_CXXFLAGS = \
20 21
	$(AM_CXXFLAGS) \
21 22
	$(GLPK_CFLAGS) \
22 23
	$(CPLEX_CFLAGS) \
23 24
	$(SOPLEX_CXXFLAGS) \
24 25
	$(CLP_CXXFLAGS) \
25 26
	$(CBC_CXXFLAGS)
26 27

	
27 28
lemon_libemon_la_LDFLAGS = \
28 29
	$(GLPK_LIBS) \
29 30
	$(CPLEX_LIBS) \
30 31
	$(SOPLEX_LIBS) \
31 32
	$(CLP_LIBS) \
32 33
	$(CBC_LIBS)
33 34

	
34 35
if HAVE_GLPK
35 36
lemon_libemon_la_SOURCES += lemon/glpk.cc
36 37
endif
37 38

	
38 39
if HAVE_CPLEX
39 40
lemon_libemon_la_SOURCES += lemon/cplex.cc
40 41
endif
41 42

	
42 43
if HAVE_SOPLEX
43 44
lemon_libemon_la_SOURCES += lemon/soplex.cc
44 45
endif
45 46

	
46 47
if HAVE_CLP
47 48
lemon_libemon_la_SOURCES += lemon/clp.cc
48 49
endif
49 50

	
50 51
if HAVE_CBC
51 52
lemon_libemon_la_SOURCES += lemon/cbc.cc
52 53
endif
53 54

	
54 55
lemon_HEADERS += \
55 56
	lemon/adaptors.h \
56 57
	lemon/arg_parser.h \
57 58
	lemon/assert.h \
58 59
	lemon/bfs.h \
59 60
	lemon/bin_heap.h \
61
	lemon/cbc.h \
60 62
	lemon/circulation.h \
61 63
	lemon/clp.h \
62 64
	lemon/color.h \
63 65
	lemon/concept_check.h \
64
	lemon/config.h \
65 66
	lemon/connectivity.h \
66 67
	lemon/counter.h \
67 68
	lemon/core.h \
68 69
	lemon/cplex.h \
69 70
	lemon/dfs.h \
70 71
	lemon/dijkstra.h \
71 72
	lemon/dim2.h \
72 73
	lemon/dimacs.h \
73 74
	lemon/edge_set.h \
74 75
	lemon/elevator.h \
75 76
	lemon/error.h \
76 77
	lemon/euler.h \
77 78
	lemon/full_graph.h \
78 79
	lemon/glpk.h \
79 80
	lemon/gomory_hu.h \
80 81
	lemon/graph_to_eps.h \
81 82
	lemon/grid_graph.h \
82 83
	lemon/hypercube_graph.h \
83 84
	lemon/kruskal.h \
84 85
	lemon/hao_orlin.h \
85 86
	lemon/lgf_reader.h \
86 87
	lemon/lgf_writer.h \
87 88
	lemon/list_graph.h \
88 89
	lemon/lp.h \
89 90
	lemon/lp_base.h \
90 91
	lemon/lp_skeleton.h \
91 92
	lemon/list_graph.h \
92 93
	lemon/maps.h \
93 94
	lemon/matching.h \
94 95
	lemon/math.h \
95 96
	lemon/min_cost_arborescence.h \
96 97
	lemon/nauty_reader.h \
97 98
	lemon/network_simplex.h \
98 99
	lemon/path.h \
99 100
	lemon/preflow.h \
100 101
	lemon/radix_sort.h \
101 102
	lemon/random.h \
102 103
	lemon/smart_graph.h \
103 104
	lemon/soplex.h \
104 105
	lemon/suurballe.h \
105 106
	lemon/time_measure.h \
106 107
	lemon/tolerance.h \
107 108
	lemon/unionfind.h \
108 109
	lemon/bits/windows.h
109 110

	
110 111
bits_HEADERS += \
111 112
	lemon/bits/alteration_notifier.h \
112 113
	lemon/bits/array_map.h \
113 114
	lemon/bits/base_extender.h \
114 115
	lemon/bits/bezier.h \
115 116
	lemon/bits/default_map.h \
116 117
	lemon/bits/edge_set_extender.h \
117 118
	lemon/bits/enable_if.h \
118 119
	lemon/bits/graph_adaptor_extender.h \
119 120
	lemon/bits/graph_extender.h \
120 121
	lemon/bits/map_extender.h \
121 122
	lemon/bits/path_dump.h \
122 123
	lemon/bits/solver_bits.h \
123 124
	lemon/bits/traits.h \
124 125
	lemon/bits/variant.h \
125 126
	lemon/bits/vector_map.h
126 127

	
127 128
concept_HEADERS += \
128 129
	lemon/concepts/digraph.h \
129 130
	lemon/concepts/graph.h \
130 131
	lemon/concepts/graph_components.h \
131 132
	lemon/concepts/heap.h \
132 133
	lemon/concepts/maps.h \
133 134
	lemon/concepts/path.h
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_CIRCULATION_H
20 20
#define LEMON_CIRCULATION_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24
#include <limits>
25 25

	
26 26
///\ingroup max_flow
27 27
///\file
28 28
///\brief Push-relabel algorithm for finding a feasible circulation.
29 29
///
30 30
namespace lemon {
31 31

	
32 32
  /// \brief Default traits class of Circulation class.
33 33
  ///
34 34
  /// Default traits class of Circulation class.
35 35
  ///
36 36
  /// \tparam GR Type of the digraph the algorithm runs on.
37 37
  /// \tparam LM The type of the lower bound map.
38 38
  /// \tparam UM The type of the upper bound (capacity) map.
39 39
  /// \tparam SM The type of the supply map.
40 40
  template <typename GR, typename LM,
41 41
            typename UM, typename SM>
42 42
  struct CirculationDefaultTraits {
43 43

	
44 44
    /// \brief The type of the digraph the algorithm runs on.
45 45
    typedef GR Digraph;
46 46

	
47 47
    /// \brief The type of the lower bound map.
48 48
    ///
49 49
    /// The type of the map that stores the lower bounds on the arcs.
50 50
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
51 51
    typedef LM LowerMap;
52 52

	
53 53
    /// \brief The type of the upper bound (capacity) map.
54 54
    ///
55 55
    /// The type of the map that stores the upper bounds (capacities)
56 56
    /// on the arcs.
57 57
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
58 58
    typedef UM UpperMap;
59 59

	
60 60
    /// \brief The type of supply map.
61 61
    ///
62 62
    /// The type of the map that stores the signed supply values of the 
63 63
    /// nodes. 
64 64
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
65 65
    typedef SM SupplyMap;
66 66

	
67
    /// \brief The type of the flow values.
68
    typedef typename SupplyMap::Value Flow;
67
    /// \brief The type of the flow and supply values.
68
    typedef typename SupplyMap::Value Value;
69 69

	
70 70
    /// \brief The type of the map that stores the flow values.
71 71
    ///
72 72
    /// The type of the map that stores the flow values.
73 73
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
74 74
    /// concept.
75
    typedef typename Digraph::template ArcMap<Flow> FlowMap;
75
    typedef typename Digraph::template ArcMap<Value> FlowMap;
76 76

	
77 77
    /// \brief Instantiates a FlowMap.
78 78
    ///
79 79
    /// This function instantiates a \ref FlowMap.
80 80
    /// \param digraph The digraph for which we would like to define
81 81
    /// the flow map.
82 82
    static FlowMap* createFlowMap(const Digraph& digraph) {
83 83
      return new FlowMap(digraph);
84 84
    }
85 85

	
86 86
    /// \brief The elevator type used by the algorithm.
87 87
    ///
88 88
    /// The elevator type used by the algorithm.
89 89
    ///
90 90
    /// \sa Elevator
91 91
    /// \sa LinkedElevator
92 92
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
93 93

	
94 94
    /// \brief Instantiates an Elevator.
95 95
    ///
96 96
    /// This function instantiates an \ref Elevator.
97 97
    /// \param digraph The digraph for which we would like to define
98 98
    /// the elevator.
99 99
    /// \param max_level The maximum level of the elevator.
100 100
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
101 101
      return new Elevator(digraph, max_level);
102 102
    }
103 103

	
104 104
    /// \brief The tolerance used by the algorithm
105 105
    ///
106 106
    /// The tolerance used by the algorithm to handle inexact computation.
107
    typedef lemon::Tolerance<Flow> Tolerance;
107
    typedef lemon::Tolerance<Value> Tolerance;
108 108

	
109 109
  };
110 110

	
111 111
  /**
112 112
     \brief Push-relabel algorithm for the network circulation problem.
113 113

	
114 114
     \ingroup max_flow
115 115
     This class implements a push-relabel algorithm for the \e network
116 116
     \e circulation problem.
117 117
     It is to find a feasible circulation when lower and upper bounds
118 118
     are given for the flow values on the arcs and lower bounds are
119 119
     given for the difference between the outgoing and incoming flow
120 120
     at the nodes.
121 121

	
122 122
     The exact formulation of this problem is the following.
123 123
     Let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{R}\f$
124 124
     \f$upper: A\rightarrow\mathbf{R}\cup\{\infty\}\f$ denote the lower and
125 125
     upper bounds on the arcs, for which \f$lower(uv) \leq upper(uv)\f$
126 126
     holds for all \f$uv\in A\f$, and \f$sup: V\rightarrow\mathbf{R}\f$
127 127
     denotes the signed supply values of the nodes.
128 128
     If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
129 129
     supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
130 130
     \f$-sup(u)\f$ demand.
131 131
     A feasible circulation is an \f$f: A\rightarrow\mathbf{R}\f$
132 132
     solution of the following problem.
133 133

	
134 134
     \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu)
135 135
     \geq sup(u) \quad \forall u\in V, \f]
136 136
     \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A. \f]
137 137
     
138 138
     The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
139 139
     zero or negative in order to have a feasible solution (since the sum
140 140
     of the expressions on the left-hand side of the inequalities is zero).
141 141
     It means that the total demand must be greater or equal to the total
142 142
     supply and all the supplies have to be carried out from the supply nodes,
143 143
     but there could be demands that are not satisfied.
144 144
     If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
145 145
     constraints have to be satisfied with equality, i.e. all demands
146 146
     have to be satisfied and all supplies have to be used.
147 147
     
148 148
     If you need the opposite inequalities in the supply/demand constraints
149 149
     (i.e. the total demand is less than the total supply and all the demands
150 150
     have to be satisfied while there could be supplies that are not used),
151 151
     then you could easily transform the problem to the above form by reversing
152 152
     the direction of the arcs and taking the negative of the supply values
153 153
     (e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
154 154

	
155 155
     This algorithm either calculates a feasible circulation, or provides
156 156
     a \ref barrier() "barrier", which prooves that a feasible soultion
157 157
     cannot exist.
158 158

	
159 159
     Note that this algorithm also provides a feasible solution for the
160 160
     \ref min_cost_flow "minimum cost flow problem".
161 161

	
162 162
     \tparam GR The type of the digraph the algorithm runs on.
163 163
     \tparam LM The type of the lower bound map. The default
164 164
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
165 165
     \tparam UM The type of the upper bound (capacity) map.
166 166
     The default map type is \c LM.
167 167
     \tparam SM The type of the supply map. The default map type is
168 168
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
169 169
  */
170 170
#ifdef DOXYGEN
171 171
template< typename GR,
172 172
          typename LM,
173 173
          typename UM,
174 174
          typename SM,
175 175
          typename TR >
176 176
#else
177 177
template< typename GR,
178 178
          typename LM = typename GR::template ArcMap<int>,
179 179
          typename UM = LM,
180 180
          typename SM = typename GR::template NodeMap<typename UM::Value>,
181 181
          typename TR = CirculationDefaultTraits<GR, LM, UM, SM> >
182 182
#endif
183 183
  class Circulation {
184 184
  public:
185 185

	
186 186
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
187 187
    typedef TR Traits;
188 188
    ///The type of the digraph the algorithm runs on.
189 189
    typedef typename Traits::Digraph Digraph;
190
    ///The type of the flow values.
191
    typedef typename Traits::Flow Flow;
190
    ///The type of the flow and supply values.
191
    typedef typename Traits::Value Value;
192 192

	
193 193
    ///The type of the lower bound map.
194 194
    typedef typename Traits::LowerMap LowerMap;
195 195
    ///The type of the upper bound (capacity) map.
196 196
    typedef typename Traits::UpperMap UpperMap;
197 197
    ///The type of the supply map.
198 198
    typedef typename Traits::SupplyMap SupplyMap;
199 199
    ///The type of the flow map.
200 200
    typedef typename Traits::FlowMap FlowMap;
201 201

	
202 202
    ///The type of the elevator.
203 203
    typedef typename Traits::Elevator Elevator;
204 204
    ///The type of the tolerance.
205 205
    typedef typename Traits::Tolerance Tolerance;
206 206

	
207 207
  private:
208 208

	
209 209
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
210 210

	
211 211
    const Digraph &_g;
212 212
    int _node_num;
213 213

	
214 214
    const LowerMap *_lo;
215 215
    const UpperMap *_up;
216 216
    const SupplyMap *_supply;
217 217

	
218 218
    FlowMap *_flow;
219 219
    bool _local_flow;
220 220

	
221 221
    Elevator* _level;
222 222
    bool _local_level;
223 223

	
224
    typedef typename Digraph::template NodeMap<Flow> ExcessMap;
224
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
225 225
    ExcessMap* _excess;
226 226

	
227 227
    Tolerance _tol;
228 228
    int _el;
229 229

	
230 230
  public:
231 231

	
232 232
    typedef Circulation Create;
233 233

	
234 234
    ///\name Named Template Parameters
235 235

	
236 236
    ///@{
237 237

	
238 238
    template <typename T>
239 239
    struct SetFlowMapTraits : public Traits {
240 240
      typedef T FlowMap;
241 241
      static FlowMap *createFlowMap(const Digraph&) {
242 242
        LEMON_ASSERT(false, "FlowMap is not initialized");
243 243
        return 0; // ignore warnings
244 244
      }
245 245
    };
246 246

	
247 247
    /// \brief \ref named-templ-param "Named parameter" for setting
248 248
    /// FlowMap type
249 249
    ///
250 250
    /// \ref named-templ-param "Named parameter" for setting FlowMap
251 251
    /// type.
252 252
    template <typename T>
253 253
    struct SetFlowMap
254 254
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
255 255
                           SetFlowMapTraits<T> > {
256 256
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
257 257
                          SetFlowMapTraits<T> > Create;
258 258
    };
259 259

	
260 260
    template <typename T>
261 261
    struct SetElevatorTraits : public Traits {
262 262
      typedef T Elevator;
263 263
      static Elevator *createElevator(const Digraph&, int) {
264 264
        LEMON_ASSERT(false, "Elevator is not initialized");
265 265
        return 0; // ignore warnings
266 266
      }
267 267
    };
268 268

	
269 269
    /// \brief \ref named-templ-param "Named parameter" for setting
270 270
    /// Elevator type
271 271
    ///
272 272
    /// \ref named-templ-param "Named parameter" for setting Elevator
273 273
    /// type. If this named parameter is used, then an external
274 274
    /// elevator object must be passed to the algorithm using the
275 275
    /// \ref elevator(Elevator&) "elevator()" function before calling
276 276
    /// \ref run() or \ref init().
277 277
    /// \sa SetStandardElevator
278 278
    template <typename T>
279 279
    struct SetElevator
280 280
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
281 281
                           SetElevatorTraits<T> > {
282 282
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
283 283
                          SetElevatorTraits<T> > Create;
284 284
    };
285 285

	
286 286
    template <typename T>
287 287
    struct SetStandardElevatorTraits : public Traits {
288 288
      typedef T Elevator;
289 289
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
290 290
        return new Elevator(digraph, max_level);
291 291
      }
292 292
    };
293 293

	
294 294
    /// \brief \ref named-templ-param "Named parameter" for setting
295 295
    /// Elevator type with automatic allocation
296 296
    ///
297 297
    /// \ref named-templ-param "Named parameter" for setting Elevator
298 298
    /// type with automatic allocation.
299 299
    /// The Elevator should have standard constructor interface to be
300 300
    /// able to automatically created by the algorithm (i.e. the
301 301
    /// digraph and the maximum level should be passed to it).
302 302
    /// However an external elevator object could also be passed to the
303 303
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
304 304
    /// before calling \ref run() or \ref init().
305 305
    /// \sa SetElevator
306 306
    template <typename T>
307 307
    struct SetStandardElevator
308 308
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
309 309
                       SetStandardElevatorTraits<T> > {
310 310
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
311 311
                      SetStandardElevatorTraits<T> > Create;
312 312
    };
313 313

	
314 314
    /// @}
315 315

	
316 316
  protected:
317 317

	
318 318
    Circulation() {}
319 319

	
320 320
  public:
321 321

	
322 322
    /// Constructor.
323 323

	
324 324
    /// The constructor of the class.
325 325
    ///
326 326
    /// \param graph The digraph the algorithm runs on.
327 327
    /// \param lower The lower bounds for the flow values on the arcs.
328 328
    /// \param upper The upper bounds (capacities) for the flow values 
329 329
    /// on the arcs.
330 330
    /// \param supply The signed supply values of the nodes.
331 331
    Circulation(const Digraph &graph, const LowerMap &lower,
332 332
                const UpperMap &upper, const SupplyMap &supply)
333 333
      : _g(graph), _lo(&lower), _up(&upper), _supply(&supply),
334 334
        _flow(NULL), _local_flow(false), _level(NULL), _local_level(false),
335 335
        _excess(NULL) {}
336 336

	
337 337
    /// Destructor.
338 338
    ~Circulation() {
339 339
      destroyStructures();
340 340
    }
341 341

	
342 342

	
343 343
  private:
344 344

	
345 345
    bool checkBoundMaps() {
346 346
      for (ArcIt e(_g);e!=INVALID;++e) {
347 347
        if (_tol.less((*_up)[e], (*_lo)[e])) return false;
348 348
      }
349 349
      return true;
350 350
    }
351 351

	
352 352
    void createStructures() {
353 353
      _node_num = _el = countNodes(_g);
354 354

	
355 355
      if (!_flow) {
356 356
        _flow = Traits::createFlowMap(_g);
357 357
        _local_flow = true;
358 358
      }
359 359
      if (!_level) {
360 360
        _level = Traits::createElevator(_g, _node_num);
361 361
        _local_level = true;
362 362
      }
363 363
      if (!_excess) {
364 364
        _excess = new ExcessMap(_g);
365 365
      }
366 366
    }
367 367

	
368 368
    void destroyStructures() {
369 369
      if (_local_flow) {
370 370
        delete _flow;
371 371
      }
372 372
      if (_local_level) {
373 373
        delete _level;
374 374
      }
375 375
      if (_excess) {
376 376
        delete _excess;
377 377
      }
378 378
    }
379 379

	
380 380
  public:
381 381

	
382 382
    /// Sets the lower bound map.
383 383

	
384 384
    /// Sets the lower bound map.
385 385
    /// \return <tt>(*this)</tt>
386 386
    Circulation& lowerMap(const LowerMap& map) {
387 387
      _lo = &map;
388 388
      return *this;
389 389
    }
390 390

	
391 391
    /// Sets the upper bound (capacity) map.
392 392

	
393 393
    /// Sets the upper bound (capacity) map.
394 394
    /// \return <tt>(*this)</tt>
395 395
    Circulation& upperMap(const UpperMap& map) {
396 396
      _up = &map;
397 397
      return *this;
398 398
    }
399 399

	
400 400
    /// Sets the supply map.
401 401

	
402 402
    /// Sets the supply map.
403 403
    /// \return <tt>(*this)</tt>
404 404
    Circulation& supplyMap(const SupplyMap& map) {
405 405
      _supply = &map;
406 406
      return *this;
407 407
    }
408 408

	
409 409
    /// \brief Sets the flow map.
410 410
    ///
411 411
    /// Sets the flow map.
412 412
    /// If you don't use this function before calling \ref run() or
413 413
    /// \ref init(), an instance will be allocated automatically.
414 414
    /// The destructor deallocates this automatically allocated map,
415 415
    /// of course.
416 416
    /// \return <tt>(*this)</tt>
417 417
    Circulation& flowMap(FlowMap& map) {
418 418
      if (_local_flow) {
419 419
        delete _flow;
420 420
        _local_flow = false;
421 421
      }
422 422
      _flow = &map;
423 423
      return *this;
424 424
    }
425 425

	
426 426
    /// \brief Sets the elevator used by algorithm.
427 427
    ///
428 428
    /// Sets the elevator used by algorithm.
429 429
    /// If you don't use this function before calling \ref run() or
430 430
    /// \ref init(), an instance will be allocated automatically.
431 431
    /// The destructor deallocates this automatically allocated elevator,
432 432
    /// of course.
433 433
    /// \return <tt>(*this)</tt>
434 434
    Circulation& elevator(Elevator& elevator) {
435 435
      if (_local_level) {
436 436
        delete _level;
437 437
        _local_level = false;
438 438
      }
439 439
      _level = &elevator;
440 440
      return *this;
441 441
    }
442 442

	
443 443
    /// \brief Returns a const reference to the elevator.
444 444
    ///
445 445
    /// Returns a const reference to the elevator.
446 446
    ///
447 447
    /// \pre Either \ref run() or \ref init() must be called before
448 448
    /// using this function.
449 449
    const Elevator& elevator() const {
450 450
      return *_level;
451 451
    }
452 452

	
453 453
    /// \brief Sets the tolerance used by algorithm.
454 454
    ///
455 455
    /// Sets the tolerance used by algorithm.
456 456
    Circulation& tolerance(const Tolerance& tolerance) const {
457 457
      _tol = tolerance;
458 458
      return *this;
459 459
    }
460 460

	
461 461
    /// \brief Returns a const reference to the tolerance.
462 462
    ///
463 463
    /// Returns a const reference to the tolerance.
464 464
    const Tolerance& tolerance() const {
465 465
      return tolerance;
466 466
    }
467 467

	
468 468
    /// \name Execution Control
469 469
    /// The simplest way to execute the algorithm is to call \ref run().\n
470 470
    /// If you need more control on the initial solution or the execution,
471 471
    /// first you have to call one of the \ref init() functions, then
472 472
    /// the \ref start() function.
473 473

	
474 474
    ///@{
475 475

	
476 476
    /// Initializes the internal data structures.
477 477

	
478 478
    /// Initializes the internal data structures and sets all flow values
479 479
    /// to the lower bound.
480 480
    void init()
481 481
    {
482 482
      LEMON_DEBUG(checkBoundMaps(),
483 483
        "Upper bounds must be greater or equal to the lower bounds");
484 484

	
485 485
      createStructures();
486 486

	
487 487
      for(NodeIt n(_g);n!=INVALID;++n) {
488 488
        (*_excess)[n] = (*_supply)[n];
489 489
      }
490 490

	
491 491
      for (ArcIt e(_g);e!=INVALID;++e) {
492 492
        _flow->set(e, (*_lo)[e]);
493 493
        (*_excess)[_g.target(e)] += (*_flow)[e];
494 494
        (*_excess)[_g.source(e)] -= (*_flow)[e];
495 495
      }
496 496

	
497 497
      // global relabeling tested, but in general case it provides
498 498
      // worse performance for random digraphs
499 499
      _level->initStart();
500 500
      for(NodeIt n(_g);n!=INVALID;++n)
501 501
        _level->initAddItem(n);
502 502
      _level->initFinish();
503 503
      for(NodeIt n(_g);n!=INVALID;++n)
504 504
        if(_tol.positive((*_excess)[n]))
505 505
          _level->activate(n);
506 506
    }
507 507

	
508 508
    /// Initializes the internal data structures using a greedy approach.
509 509

	
510 510
    /// Initializes the internal data structures using a greedy approach
511 511
    /// to construct the initial solution.
512 512
    void greedyInit()
513 513
    {
514 514
      LEMON_DEBUG(checkBoundMaps(),
515 515
        "Upper bounds must be greater or equal to the lower bounds");
516 516

	
517 517
      createStructures();
518 518

	
519 519
      for(NodeIt n(_g);n!=INVALID;++n) {
520 520
        (*_excess)[n] = (*_supply)[n];
521 521
      }
522 522

	
523 523
      for (ArcIt e(_g);e!=INVALID;++e) {
524 524
        if (!_tol.less(-(*_excess)[_g.target(e)], (*_up)[e])) {
525 525
          _flow->set(e, (*_up)[e]);
526 526
          (*_excess)[_g.target(e)] += (*_up)[e];
527 527
          (*_excess)[_g.source(e)] -= (*_up)[e];
528 528
        } else if (_tol.less(-(*_excess)[_g.target(e)], (*_lo)[e])) {
529 529
          _flow->set(e, (*_lo)[e]);
530 530
          (*_excess)[_g.target(e)] += (*_lo)[e];
531 531
          (*_excess)[_g.source(e)] -= (*_lo)[e];
532 532
        } else {
533
          Flow fc = -(*_excess)[_g.target(e)];
533
          Value fc = -(*_excess)[_g.target(e)];
534 534
          _flow->set(e, fc);
535 535
          (*_excess)[_g.target(e)] = 0;
536 536
          (*_excess)[_g.source(e)] -= fc;
537 537
        }
538 538
      }
539 539

	
540 540
      _level->initStart();
541 541
      for(NodeIt n(_g);n!=INVALID;++n)
542 542
        _level->initAddItem(n);
543 543
      _level->initFinish();
544 544
      for(NodeIt n(_g);n!=INVALID;++n)
545 545
        if(_tol.positive((*_excess)[n]))
546 546
          _level->activate(n);
547 547
    }
548 548

	
549 549
    ///Executes the algorithm
550 550

	
551 551
    ///This function executes the algorithm.
552 552
    ///
553 553
    ///\return \c true if a feasible circulation is found.
554 554
    ///
555 555
    ///\sa barrier()
556 556
    ///\sa barrierMap()
557 557
    bool start()
558 558
    {
559 559

	
560 560
      Node act;
561 561
      Node bact=INVALID;
562 562
      Node last_activated=INVALID;
563 563
      while((act=_level->highestActive())!=INVALID) {
564 564
        int actlevel=(*_level)[act];
565 565
        int mlevel=_node_num;
566
        Flow exc=(*_excess)[act];
566
        Value exc=(*_excess)[act];
567 567

	
568 568
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
569 569
          Node v = _g.target(e);
570
          Flow fc=(*_up)[e]-(*_flow)[e];
570
          Value fc=(*_up)[e]-(*_flow)[e];
571 571
          if(!_tol.positive(fc)) continue;
572 572
          if((*_level)[v]<actlevel) {
573 573
            if(!_tol.less(fc, exc)) {
574 574
              _flow->set(e, (*_flow)[e] + exc);
575 575
              (*_excess)[v] += exc;
576 576
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
577 577
                _level->activate(v);
578 578
              (*_excess)[act] = 0;
579 579
              _level->deactivate(act);
580 580
              goto next_l;
581 581
            }
582 582
            else {
583 583
              _flow->set(e, (*_up)[e]);
584 584
              (*_excess)[v] += fc;
585 585
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
586 586
                _level->activate(v);
587 587
              exc-=fc;
588 588
            }
589 589
          }
590 590
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
591 591
        }
592 592
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
593 593
          Node v = _g.source(e);
594
          Flow fc=(*_flow)[e]-(*_lo)[e];
594
          Value fc=(*_flow)[e]-(*_lo)[e];
595 595
          if(!_tol.positive(fc)) continue;
596 596
          if((*_level)[v]<actlevel) {
597 597
            if(!_tol.less(fc, exc)) {
598 598
              _flow->set(e, (*_flow)[e] - exc);
599 599
              (*_excess)[v] += exc;
600 600
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
601 601
                _level->activate(v);
602 602
              (*_excess)[act] = 0;
603 603
              _level->deactivate(act);
604 604
              goto next_l;
605 605
            }
606 606
            else {
607 607
              _flow->set(e, (*_lo)[e]);
608 608
              (*_excess)[v] += fc;
609 609
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
610 610
                _level->activate(v);
611 611
              exc-=fc;
612 612
            }
613 613
          }
614 614
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
615 615
        }
616 616

	
617 617
        (*_excess)[act] = exc;
618 618
        if(!_tol.positive(exc)) _level->deactivate(act);
619 619
        else if(mlevel==_node_num) {
620 620
          _level->liftHighestActiveToTop();
621 621
          _el = _node_num;
622 622
          return false;
623 623
        }
624 624
        else {
625 625
          _level->liftHighestActive(mlevel+1);
626 626
          if(_level->onLevel(actlevel)==0) {
627 627
            _el = actlevel;
628 628
            return false;
629 629
          }
630 630
        }
631 631
      next_l:
632 632
        ;
633 633
      }
634 634
      return true;
635 635
    }
636 636

	
637 637
    /// Runs the algorithm.
638 638

	
639 639
    /// This function runs the algorithm.
640 640
    ///
641 641
    /// \return \c true if a feasible circulation is found.
642 642
    ///
643 643
    /// \note Apart from the return value, c.run() is just a shortcut of
644 644
    /// the following code.
645 645
    /// \code
646 646
    ///   c.greedyInit();
647 647
    ///   c.start();
648 648
    /// \endcode
649 649
    bool run() {
650 650
      greedyInit();
651 651
      return start();
652 652
    }
653 653

	
654 654
    /// @}
655 655

	
656 656
    /// \name Query Functions
657 657
    /// The results of the circulation algorithm can be obtained using
658 658
    /// these functions.\n
659 659
    /// Either \ref run() or \ref start() should be called before
660 660
    /// using them.
661 661

	
662 662
    ///@{
663 663

	
664
    /// \brief Returns the flow on the given arc.
664
    /// \brief Returns the flow value on the given arc.
665 665
    ///
666
    /// Returns the flow on the given arc.
666
    /// Returns the flow value on the given arc.
667 667
    ///
668 668
    /// \pre Either \ref run() or \ref init() must be called before
669 669
    /// using this function.
670
    Flow flow(const Arc& arc) const {
670
    Value flow(const Arc& arc) const {
671 671
      return (*_flow)[arc];
672 672
    }
673 673

	
674 674
    /// \brief Returns a const reference to the flow map.
675 675
    ///
676 676
    /// Returns a const reference to the arc map storing the found flow.
677 677
    ///
678 678
    /// \pre Either \ref run() or \ref init() must be called before
679 679
    /// using this function.
680 680
    const FlowMap& flowMap() const {
681 681
      return *_flow;
682 682
    }
683 683

	
684 684
    /**
685 685
       \brief Returns \c true if the given node is in a barrier.
686 686

	
687 687
       Barrier is a set \e B of nodes for which
688 688

	
689 689
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
690 690
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
691 691

	
692 692
       holds. The existence of a set with this property prooves that a
693 693
       feasible circualtion cannot exist.
694 694

	
695 695
       This function returns \c true if the given node is in the found
696 696
       barrier. If a feasible circulation is found, the function
697 697
       gives back \c false for every node.
698 698

	
699 699
       \pre Either \ref run() or \ref init() must be called before
700 700
       using this function.
701 701

	
702 702
       \sa barrierMap()
703 703
       \sa checkBarrier()
704 704
    */
705 705
    bool barrier(const Node& node) const
706 706
    {
707 707
      return (*_level)[node] >= _el;
708 708
    }
709 709

	
710 710
    /// \brief Gives back a barrier.
711 711
    ///
712 712
    /// This function sets \c bar to the characteristic vector of the
713 713
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
714 714
    /// node map with \c bool (or convertible) value type.
715 715
    ///
716 716
    /// If a feasible circulation is found, the function gives back an
717 717
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
718 718
    ///
719 719
    /// \note This function calls \ref barrier() for each node,
720 720
    /// so it runs in O(n) time.
721 721
    ///
722 722
    /// \pre Either \ref run() or \ref init() must be called before
723 723
    /// using this function.
724 724
    ///
725 725
    /// \sa barrier()
726 726
    /// \sa checkBarrier()
727 727
    template<class BarrierMap>
728 728
    void barrierMap(BarrierMap &bar) const
729 729
    {
730 730
      for(NodeIt n(_g);n!=INVALID;++n)
731 731
        bar.set(n, (*_level)[n] >= _el);
732 732
    }
733 733

	
734 734
    /// @}
735 735

	
736 736
    /// \name Checker Functions
737 737
    /// The feasibility of the results can be checked using
738 738
    /// these functions.\n
739 739
    /// Either \ref run() or \ref start() should be called before
740 740
    /// using them.
741 741

	
742 742
    ///@{
743 743

	
744 744
    ///Check if the found flow is a feasible circulation
745 745

	
746 746
    ///Check if the found flow is a feasible circulation,
747 747
    ///
748 748
    bool checkFlow() const {
749 749
      for(ArcIt e(_g);e!=INVALID;++e)
750 750
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
751 751
      for(NodeIt n(_g);n!=INVALID;++n)
752 752
        {
753
          Flow dif=-(*_supply)[n];
753
          Value dif=-(*_supply)[n];
754 754
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
755 755
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
756 756
          if(_tol.negative(dif)) return false;
757 757
        }
758 758
      return true;
759 759
    }
760 760

	
761 761
    ///Check whether or not the last execution provides a barrier
762 762

	
763 763
    ///Check whether or not the last execution provides a barrier.
764 764
    ///\sa barrier()
765 765
    ///\sa barrierMap()
766 766
    bool checkBarrier() const
767 767
    {
768
      Flow delta=0;
769
      Flow inf_cap = std::numeric_limits<Flow>::has_infinity ?
770
        std::numeric_limits<Flow>::infinity() :
771
        std::numeric_limits<Flow>::max();
768
      Value delta=0;
769
      Value inf_cap = std::numeric_limits<Value>::has_infinity ?
770
        std::numeric_limits<Value>::infinity() :
771
        std::numeric_limits<Value>::max();
772 772
      for(NodeIt n(_g);n!=INVALID;++n)
773 773
        if(barrier(n))
774 774
          delta-=(*_supply)[n];
775 775
      for(ArcIt e(_g);e!=INVALID;++e)
776 776
        {
777 777
          Node s=_g.source(e);
778 778
          Node t=_g.target(e);
779 779
          if(barrier(s)&&!barrier(t)) {
780 780
            if (_tol.less(inf_cap - (*_up)[e], delta)) return false;
781 781
            delta+=(*_up)[e];
782 782
          }
783 783
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
784 784
        }
785 785
      return _tol.negative(delta);
786 786
    }
787 787

	
788 788
    /// @}
789 789

	
790 790
  };
791 791

	
792 792
}
793 793

	
794 794
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_CORE_H
20 20
#define LEMON_CORE_H
21 21

	
22 22
#include <vector>
23 23
#include <algorithm>
24 24

	
25
#include <lemon/core.h>
25
#include <lemon/config.h>
26 26
#include <lemon/bits/enable_if.h>
27 27
#include <lemon/bits/traits.h>
28 28
#include <lemon/assert.h>
29 29

	
30 30
///\file
31 31
///\brief LEMON core utilities.
32 32
///
33 33
///This header file contains core utilities for LEMON.
34 34
///It is automatically included by all graph types, therefore it usually
35 35
///do not have to be included directly.
36 36

	
37 37
namespace lemon {
38 38

	
39 39
  /// \brief Dummy type to make it easier to create invalid iterators.
40 40
  ///
41 41
  /// Dummy type to make it easier to create invalid iterators.
42 42
  /// See \ref INVALID for the usage.
43 43
  struct Invalid {
44 44
  public:
45 45
    bool operator==(Invalid) { return true;  }
46 46
    bool operator!=(Invalid) { return false; }
47 47
    bool operator< (Invalid) { return false; }
48 48
  };
49 49

	
50 50
  /// \brief Invalid iterators.
51 51
  ///
52 52
  /// \ref Invalid is a global type that converts to each iterator
53 53
  /// in such a way that the value of the target iterator will be invalid.
54 54
#ifdef LEMON_ONLY_TEMPLATES
55 55
  const Invalid INVALID = Invalid();
56 56
#else
57 57
  extern const Invalid INVALID;
58 58
#endif
59 59

	
60 60
  /// \addtogroup gutils
61 61
  /// @{
62 62

	
63 63
  ///Create convenience typedefs for the digraph types and iterators
64 64

	
65 65
  ///This \c \#define creates convenient type definitions for the following
66 66
  ///types of \c Digraph: \c Node,  \c NodeIt, \c Arc, \c ArcIt, \c InArcIt,
67 67
  ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap,
68 68
  ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap.
69 69
  ///
70 70
  ///\note If the graph type is a dependent type, ie. the graph type depend
71 71
  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
72 72
  ///macro.
73 73
#define DIGRAPH_TYPEDEFS(Digraph)                                       \
74 74
  typedef Digraph::Node Node;                                           \
75 75
  typedef Digraph::NodeIt NodeIt;                                       \
76 76
  typedef Digraph::Arc Arc;                                             \
77 77
  typedef Digraph::ArcIt ArcIt;                                         \
78 78
  typedef Digraph::InArcIt InArcIt;                                     \
79 79
  typedef Digraph::OutArcIt OutArcIt;                                   \
80 80
  typedef Digraph::NodeMap<bool> BoolNodeMap;                           \
81 81
  typedef Digraph::NodeMap<int> IntNodeMap;                             \
82 82
  typedef Digraph::NodeMap<double> DoubleNodeMap;                       \
83 83
  typedef Digraph::ArcMap<bool> BoolArcMap;                             \
84 84
  typedef Digraph::ArcMap<int> IntArcMap;                               \
85 85
  typedef Digraph::ArcMap<double> DoubleArcMap
86 86

	
87 87
  ///Create convenience typedefs for the digraph types and iterators
88 88

	
89 89
  ///\see DIGRAPH_TYPEDEFS
90 90
  ///
91 91
  ///\note Use this macro, if the graph type is a dependent type,
92 92
  ///ie. the graph type depend on a template parameter.
93 93
#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph)                              \
94 94
  typedef typename Digraph::Node Node;                                  \
95 95
  typedef typename Digraph::NodeIt NodeIt;                              \
96 96
  typedef typename Digraph::Arc Arc;                                    \
97 97
  typedef typename Digraph::ArcIt ArcIt;                                \
98 98
  typedef typename Digraph::InArcIt InArcIt;                            \
99 99
  typedef typename Digraph::OutArcIt OutArcIt;                          \
100 100
  typedef typename Digraph::template NodeMap<bool> BoolNodeMap;         \
101 101
  typedef typename Digraph::template NodeMap<int> IntNodeMap;           \
102 102
  typedef typename Digraph::template NodeMap<double> DoubleNodeMap;     \
103 103
  typedef typename Digraph::template ArcMap<bool> BoolArcMap;           \
104 104
  typedef typename Digraph::template ArcMap<int> IntArcMap;             \
105 105
  typedef typename Digraph::template ArcMap<double> DoubleArcMap
106 106

	
107 107
  ///Create convenience typedefs for the graph types and iterators
108 108

	
109 109
  ///This \c \#define creates the same convenient type definitions as defined
110 110
  ///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates
111 111
  ///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap,
112 112
  ///\c DoubleEdgeMap.
113 113
  ///
114 114
  ///\note If the graph type is a dependent type, ie. the graph type depend
115 115
  ///on a template parameter, then use \c TEMPLATE_GRAPH_TYPEDEFS()
116 116
  ///macro.
117 117
#define GRAPH_TYPEDEFS(Graph)                                           \
118 118
  DIGRAPH_TYPEDEFS(Graph);                                              \
119 119
  typedef Graph::Edge Edge;                                             \
120 120
  typedef Graph::EdgeIt EdgeIt;                                         \
121 121
  typedef Graph::IncEdgeIt IncEdgeIt;                                   \
122 122
  typedef Graph::EdgeMap<bool> BoolEdgeMap;                             \
123 123
  typedef Graph::EdgeMap<int> IntEdgeMap;                               \
124 124
  typedef Graph::EdgeMap<double> DoubleEdgeMap
125 125

	
126 126
  ///Create convenience typedefs for the graph types and iterators
127 127

	
128 128
  ///\see GRAPH_TYPEDEFS
129 129
  ///
130 130
  ///\note Use this macro, if the graph type is a dependent type,
131 131
  ///ie. the graph type depend on a template parameter.
132 132
#define TEMPLATE_GRAPH_TYPEDEFS(Graph)                                  \
133 133
  TEMPLATE_DIGRAPH_TYPEDEFS(Graph);                                     \
134 134
  typedef typename Graph::Edge Edge;                                    \
135 135
  typedef typename Graph::EdgeIt EdgeIt;                                \
136 136
  typedef typename Graph::IncEdgeIt IncEdgeIt;                          \
137 137
  typedef typename Graph::template EdgeMap<bool> BoolEdgeMap;           \
138 138
  typedef typename Graph::template EdgeMap<int> IntEdgeMap;             \
139 139
  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
140 140

	
141 141
  /// \brief Function to count the items in a graph.
142 142
  ///
143 143
  /// This function counts the items (nodes, arcs etc.) in a graph.
144 144
  /// The complexity of the function is linear because
145 145
  /// it iterates on all of the items.
146 146
  template <typename Graph, typename Item>
147 147
  inline int countItems(const Graph& g) {
148 148
    typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt;
149 149
    int num = 0;
150 150
    for (ItemIt it(g); it != INVALID; ++it) {
151 151
      ++num;
152 152
    }
153 153
    return num;
154 154
  }
155 155

	
156 156
  // Node counting:
157 157

	
158 158
  namespace _core_bits {
159 159

	
160 160
    template <typename Graph, typename Enable = void>
161 161
    struct CountNodesSelector {
162 162
      static int count(const Graph &g) {
163 163
        return countItems<Graph, typename Graph::Node>(g);
164 164
      }
165 165
    };
166 166

	
167 167
    template <typename Graph>
168 168
    struct CountNodesSelector<
169 169
      Graph, typename
170 170
      enable_if<typename Graph::NodeNumTag, void>::type>
171 171
    {
172 172
      static int count(const Graph &g) {
173 173
        return g.nodeNum();
174 174
      }
175 175
    };
176 176
  }
177 177

	
178 178
  /// \brief Function to count the nodes in the graph.
179 179
  ///
180 180
  /// This function counts the nodes in the graph.
181 181
  /// The complexity of the function is <em>O</em>(<em>n</em>), but for some
182 182
  /// graph structures it is specialized to run in <em>O</em>(1).
183 183
  ///
184 184
  /// \note If the graph contains a \c nodeNum() member function and a
185 185
  /// \c NodeNumTag tag then this function calls directly the member
186 186
  /// function to query the cardinality of the node set.
187 187
  template <typename Graph>
188 188
  inline int countNodes(const Graph& g) {
189 189
    return _core_bits::CountNodesSelector<Graph>::count(g);
190 190
  }
191 191

	
192 192
  // Arc counting:
193 193

	
194 194
  namespace _core_bits {
195 195

	
196 196
    template <typename Graph, typename Enable = void>
197 197
    struct CountArcsSelector {
198 198
      static int count(const Graph &g) {
199 199
        return countItems<Graph, typename Graph::Arc>(g);
200 200
      }
201 201
    };
202 202

	
203 203
    template <typename Graph>
204 204
    struct CountArcsSelector<
205 205
      Graph,
206 206
      typename enable_if<typename Graph::ArcNumTag, void>::type>
207 207
    {
208 208
      static int count(const Graph &g) {
209 209
        return g.arcNum();
210 210
      }
211 211
    };
212 212
  }
213 213

	
214 214
  /// \brief Function to count the arcs in the graph.
215 215
  ///
216 216
  /// This function counts the arcs in the graph.
217 217
  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
218 218
  /// graph structures it is specialized to run in <em>O</em>(1).
219 219
  ///
220 220
  /// \note If the graph contains a \c arcNum() member function and a
221 221
  /// \c ArcNumTag tag then this function calls directly the member
222 222
  /// function to query the cardinality of the arc set.
223 223
  template <typename Graph>
224 224
  inline int countArcs(const Graph& g) {
225 225
    return _core_bits::CountArcsSelector<Graph>::count(g);
226 226
  }
227 227

	
228 228
  // Edge counting:
229 229

	
230 230
  namespace _core_bits {
231 231

	
232 232
    template <typename Graph, typename Enable = void>
233 233
    struct CountEdgesSelector {
234 234
      static int count(const Graph &g) {
235 235
        return countItems<Graph, typename Graph::Edge>(g);
236 236
      }
237 237
    };
238 238

	
239 239
    template <typename Graph>
240 240
    struct CountEdgesSelector<
241 241
      Graph,
242 242
      typename enable_if<typename Graph::EdgeNumTag, void>::type>
243 243
    {
244 244
      static int count(const Graph &g) {
245 245
        return g.edgeNum();
246 246
      }
247 247
    };
248 248
  }
249 249

	
250 250
  /// \brief Function to count the edges in the graph.
251 251
  ///
252 252
  /// This function counts the edges in the graph.
253 253
  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
254 254
  /// graph structures it is specialized to run in <em>O</em>(1).
255 255
  ///
256 256
  /// \note If the graph contains a \c edgeNum() member function and a
257 257
  /// \c EdgeNumTag tag then this function calls directly the member
258 258
  /// function to query the cardinality of the edge set.
259 259
  template <typename Graph>
260 260
  inline int countEdges(const Graph& g) {
261 261
    return _core_bits::CountEdgesSelector<Graph>::count(g);
262 262

	
263 263
  }
264 264

	
265 265

	
266 266
  template <typename Graph, typename DegIt>
267 267
  inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
268 268
    int num = 0;
269 269
    for (DegIt it(_g, _n); it != INVALID; ++it) {
270 270
      ++num;
271 271
    }
272 272
    return num;
273 273
  }
274 274

	
275 275
  /// \brief Function to count the number of the out-arcs from node \c n.
276 276
  ///
277 277
  /// This function counts the number of the out-arcs from node \c n
278 278
  /// in the graph \c g.
279 279
  template <typename Graph>
280 280
  inline int countOutArcs(const Graph& g,  const typename Graph::Node& n) {
281 281
    return countNodeDegree<Graph, typename Graph::OutArcIt>(g, n);
282 282
  }
283 283

	
284 284
  /// \brief Function to count the number of the in-arcs to node \c n.
285 285
  ///
286 286
  /// This function counts the number of the in-arcs to node \c n
287 287
  /// in the graph \c g.
288 288
  template <typename Graph>
289 289
  inline int countInArcs(const Graph& g,  const typename Graph::Node& n) {
290 290
    return countNodeDegree<Graph, typename Graph::InArcIt>(g, n);
291 291
  }
292 292

	
293 293
  /// \brief Function to count the number of the inc-edges to node \c n.
294 294
  ///
295 295
  /// This function counts the number of the inc-edges to node \c n
296 296
  /// in the undirected graph \c g.
297 297
  template <typename Graph>
298 298
  inline int countIncEdges(const Graph& g,  const typename Graph::Node& n) {
299 299
    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(g, n);
300 300
  }
301 301

	
302 302
  namespace _core_bits {
303 303

	
304 304
    template <typename Digraph, typename Item, typename RefMap>
305 305
    class MapCopyBase {
306 306
    public:
307 307
      virtual void copy(const Digraph& from, const RefMap& refMap) = 0;
308 308

	
309 309
      virtual ~MapCopyBase() {}
310 310
    };
311 311

	
312 312
    template <typename Digraph, typename Item, typename RefMap,
313 313
              typename FromMap, typename ToMap>
314 314
    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
315 315
    public:
316 316

	
317 317
      MapCopy(const FromMap& map, ToMap& tmap)
318 318
        : _map(map), _tmap(tmap) {}
319 319

	
320 320
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
321 321
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
322 322
        for (ItemIt it(digraph); it != INVALID; ++it) {
323 323
          _tmap.set(refMap[it], _map[it]);
324 324
        }
325 325
      }
326 326

	
327 327
    private:
328 328
      const FromMap& _map;
329 329
      ToMap& _tmap;
330 330
    };
331 331

	
332 332
    template <typename Digraph, typename Item, typename RefMap, typename It>
333 333
    class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> {
334 334
    public:
335 335

	
336 336
      ItemCopy(const Item& item, It& it) : _item(item), _it(it) {}
337 337

	
338 338
      virtual void copy(const Digraph&, const RefMap& refMap) {
339 339
        _it = refMap[_item];
340 340
      }
341 341

	
342 342
    private:
343 343
      Item _item;
344 344
      It& _it;
345 345
    };
346 346

	
347 347
    template <typename Digraph, typename Item, typename RefMap, typename Ref>
348 348
    class RefCopy : public MapCopyBase<Digraph, Item, RefMap> {
349 349
    public:
350 350

	
351 351
      RefCopy(Ref& map) : _map(map) {}
352 352

	
353 353
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
354 354
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
355 355
        for (ItemIt it(digraph); it != INVALID; ++it) {
356 356
          _map.set(it, refMap[it]);
357 357
        }
358 358
      }
359 359

	
360 360
    private:
361 361
      Ref& _map;
362 362
    };
363 363

	
364 364
    template <typename Digraph, typename Item, typename RefMap,
365 365
              typename CrossRef>
366 366
    class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> {
367 367
    public:
368 368

	
369 369
      CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {}
370 370

	
371 371
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
372 372
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
373 373
        for (ItemIt it(digraph); it != INVALID; ++it) {
374 374
          _cmap.set(refMap[it], it);
375 375
        }
376 376
      }
377 377

	
378 378
    private:
379 379
      CrossRef& _cmap;
380 380
    };
381 381

	
382 382
    template <typename Digraph, typename Enable = void>
383 383
    struct DigraphCopySelector {
384 384
      template <typename From, typename NodeRefMap, typename ArcRefMap>
385 385
      static void copy(const From& from, Digraph &to,
386 386
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
387 387
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
388 388
          nodeRefMap[it] = to.addNode();
389 389
        }
390 390
        for (typename From::ArcIt it(from); it != INVALID; ++it) {
391 391
          arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)],
392 392
                                    nodeRefMap[from.target(it)]);
393 393
        }
394 394
      }
395 395
    };
396 396

	
397 397
    template <typename Digraph>
398 398
    struct DigraphCopySelector<
399 399
      Digraph,
400 400
      typename enable_if<typename Digraph::BuildTag, void>::type>
401 401
    {
402 402
      template <typename From, typename NodeRefMap, typename ArcRefMap>
403 403
      static void copy(const From& from, Digraph &to,
404 404
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
405 405
        to.build(from, nodeRefMap, arcRefMap);
406 406
      }
407 407
    };
408 408

	
409 409
    template <typename Graph, typename Enable = void>
410 410
    struct GraphCopySelector {
411 411
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
412 412
      static void copy(const From& from, Graph &to,
413 413
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
414 414
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
415 415
          nodeRefMap[it] = to.addNode();
416 416
        }
417 417
        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
418 418
          edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)],
419 419
                                      nodeRefMap[from.v(it)]);
420 420
        }
421 421
      }
422 422
    };
423 423

	
424 424
    template <typename Graph>
425 425
    struct GraphCopySelector<
426 426
      Graph,
427 427
      typename enable_if<typename Graph::BuildTag, void>::type>
428 428
    {
429 429
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
430 430
      static void copy(const From& from, Graph &to,
431 431
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
432 432
        to.build(from, nodeRefMap, edgeRefMap);
433 433
      }
434 434
    };
435 435

	
436 436
  }
437 437

	
438 438
  /// \brief Class to copy a digraph.
439 439
  ///
440 440
  /// Class to copy a digraph to another digraph (duplicate a digraph). The
441 441
  /// simplest way of using it is through the \c digraphCopy() function.
442 442
  ///
443 443
  /// This class not only make a copy of a digraph, but it can create
444 444
  /// references and cross references between the nodes and arcs of
445 445
  /// the two digraphs, and it can copy maps to use with the newly created
446 446
  /// digraph.
447 447
  ///
448 448
  /// To make a copy from a digraph, first an instance of DigraphCopy
449 449
  /// should be created, then the data belongs to the digraph should
450 450
  /// assigned to copy. In the end, the \c run() member should be
451 451
  /// called.
452 452
  ///
453 453
  /// The next code copies a digraph with several data:
454 454
  ///\code
455 455
  ///  DigraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
456 456
  ///  // Create references for the nodes
457 457
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
458 458
  ///  cg.nodeRef(nr);
459 459
  ///  // Create cross references (inverse) for the arcs
460 460
  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
461 461
  ///  cg.arcCrossRef(acr);
462 462
  ///  // Copy an arc map
463 463
  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
464 464
  ///  NewGraph::ArcMap<double> namap(new_graph);
465 465
  ///  cg.arcMap(oamap, namap);
466 466
  ///  // Copy a node
467 467
  ///  OrigGraph::Node on;
468 468
  ///  NewGraph::Node nn;
469 469
  ///  cg.node(on, nn);
470 470
  ///  // Execute copying
471 471
  ///  cg.run();
472 472
  ///\endcode
473 473
  template <typename From, typename To>
474 474
  class DigraphCopy {
475 475
  private:
476 476

	
477 477
    typedef typename From::Node Node;
478 478
    typedef typename From::NodeIt NodeIt;
479 479
    typedef typename From::Arc Arc;
480 480
    typedef typename From::ArcIt ArcIt;
481 481

	
482 482
    typedef typename To::Node TNode;
483 483
    typedef typename To::Arc TArc;
484 484

	
485 485
    typedef typename From::template NodeMap<TNode> NodeRefMap;
486 486
    typedef typename From::template ArcMap<TArc> ArcRefMap;
487 487

	
488 488
  public:
489 489

	
490 490
    /// \brief Constructor of DigraphCopy.
491 491
    ///
492 492
    /// Constructor of DigraphCopy for copying the content of the
493 493
    /// \c from digraph into the \c to digraph.
494 494
    DigraphCopy(const From& from, To& to)
495 495
      : _from(from), _to(to) {}
496 496

	
497 497
    /// \brief Destructor of DigraphCopy
498 498
    ///
499 499
    /// Destructor of DigraphCopy.
500 500
    ~DigraphCopy() {
501 501
      for (int i = 0; i < int(_node_maps.size()); ++i) {
502 502
        delete _node_maps[i];
503 503
      }
504 504
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
505 505
        delete _arc_maps[i];
506 506
      }
507 507

	
508 508
    }
509 509

	
510 510
    /// \brief Copy the node references into the given map.
511 511
    ///
512 512
    /// This function copies the node references into the given map.
513 513
    /// The parameter should be a map, whose key type is the Node type of
514 514
    /// the source digraph, while the value type is the Node type of the
515 515
    /// destination digraph.
516 516
    template <typename NodeRef>
517 517
    DigraphCopy& nodeRef(NodeRef& map) {
518 518
      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
519 519
                           NodeRefMap, NodeRef>(map));
520 520
      return *this;
521 521
    }
522 522

	
523 523
    /// \brief Copy the node cross references into the given map.
524 524
    ///
525 525
    /// This function copies the node cross references (reverse references)
526 526
    /// into the given map. The parameter should be a map, whose key type
527 527
    /// is the Node type of the destination digraph, while the value type is
528 528
    /// the Node type of the source digraph.
529 529
    template <typename NodeCrossRef>
530 530
    DigraphCopy& nodeCrossRef(NodeCrossRef& map) {
531 531
      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
532 532
                           NodeRefMap, NodeCrossRef>(map));
533 533
      return *this;
534 534
    }
535 535

	
536 536
    /// \brief Make a copy of the given node map.
537 537
    ///
538 538
    /// This function makes a copy of the given node map for the newly
539 539
    /// created digraph.
540 540
    /// The key type of the new map \c tmap should be the Node type of the
541 541
    /// destination digraph, and the key type of the original map \c map
542 542
    /// should be the Node type of the source digraph.
543 543
    template <typename FromMap, typename ToMap>
544 544
    DigraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
545 545
      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
546 546
                           NodeRefMap, FromMap, ToMap>(map, tmap));
547 547
      return *this;
548 548
    }
549 549

	
550 550
    /// \brief Make a copy of the given node.
551 551
    ///
552 552
    /// This function makes a copy of the given node.
553 553
    DigraphCopy& node(const Node& node, TNode& tnode) {
554 554
      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
555 555
                           NodeRefMap, TNode>(node, tnode));
556 556
      return *this;
557 557
    }
558 558

	
559 559
    /// \brief Copy the arc references into the given map.
560 560
    ///
561 561
    /// This function copies the arc references into the given map.
562 562
    /// The parameter should be a map, whose key type is the Arc type of
563 563
    /// the source digraph, while the value type is the Arc type of the
564 564
    /// destination digraph.
565 565
    template <typename ArcRef>
566 566
    DigraphCopy& arcRef(ArcRef& map) {
567 567
      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
568 568
                          ArcRefMap, ArcRef>(map));
569 569
      return *this;
570 570
    }
571 571

	
572 572
    /// \brief Copy the arc cross references into the given map.
573 573
    ///
574 574
    /// This function copies the arc cross references (reverse references)
575 575
    /// into the given map. The parameter should be a map, whose key type
576 576
    /// is the Arc type of the destination digraph, while the value type is
577 577
    /// the Arc type of the source digraph.
578 578
    template <typename ArcCrossRef>
579 579
    DigraphCopy& arcCrossRef(ArcCrossRef& map) {
580 580
      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
581 581
                          ArcRefMap, ArcCrossRef>(map));
582 582
      return *this;
583 583
    }
584 584

	
585 585
    /// \brief Make a copy of the given arc map.
586 586
    ///
587 587
    /// This function makes a copy of the given arc map for the newly
588 588
    /// created digraph.
589 589
    /// The key type of the new map \c tmap should be the Arc type of the
590 590
    /// destination digraph, and the key type of the original map \c map
591 591
    /// should be the Arc type of the source digraph.
592 592
    template <typename FromMap, typename ToMap>
593 593
    DigraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
594 594
      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
595 595
                          ArcRefMap, FromMap, ToMap>(map, tmap));
596 596
      return *this;
597 597
    }
598 598

	
599 599
    /// \brief Make a copy of the given arc.
600 600
    ///
601 601
    /// This function makes a copy of the given arc.
602 602
    DigraphCopy& arc(const Arc& arc, TArc& tarc) {
603 603
      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
604 604
                          ArcRefMap, TArc>(arc, tarc));
605 605
      return *this;
606 606
    }
607 607

	
608 608
    /// \brief Execute copying.
609 609
    ///
610 610
    /// This function executes the copying of the digraph along with the
611 611
    /// copying of the assigned data.
612 612
    void run() {
613 613
      NodeRefMap nodeRefMap(_from);
614 614
      ArcRefMap arcRefMap(_from);
615 615
      _core_bits::DigraphCopySelector<To>::
616 616
        copy(_from, _to, nodeRefMap, arcRefMap);
617 617
      for (int i = 0; i < int(_node_maps.size()); ++i) {
618 618
        _node_maps[i]->copy(_from, nodeRefMap);
619 619
      }
620 620
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
621 621
        _arc_maps[i]->copy(_from, arcRefMap);
622 622
      }
623 623
    }
624 624

	
625 625
  protected:
626 626

	
627 627
    const From& _from;
628 628
    To& _to;
629 629

	
630 630
    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
631 631
      _node_maps;
632 632

	
633 633
    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
634 634
      _arc_maps;
635 635

	
636 636
  };
637 637

	
638 638
  /// \brief Copy a digraph to another digraph.
639 639
  ///
640 640
  /// This function copies a digraph to another digraph.
641 641
  /// The complete usage of it is detailed in the DigraphCopy class, but
642 642
  /// a short example shows a basic work:
643 643
  ///\code
644 644
  /// digraphCopy(src, trg).nodeRef(nr).arcCrossRef(acr).run();
645 645
  ///\endcode
646 646
  ///
647 647
  /// After the copy the \c nr map will contain the mapping from the
648 648
  /// nodes of the \c from digraph to the nodes of the \c to digraph and
649 649
  /// \c acr will contain the mapping from the arcs of the \c to digraph
650 650
  /// to the arcs of the \c from digraph.
651 651
  ///
652 652
  /// \see DigraphCopy
653 653
  template <typename From, typename To>
654 654
  DigraphCopy<From, To> digraphCopy(const From& from, To& to) {
655 655
    return DigraphCopy<From, To>(from, to);
656 656
  }
657 657

	
658 658
  /// \brief Class to copy a graph.
659 659
  ///
660 660
  /// Class to copy a graph to another graph (duplicate a graph). The
661 661
  /// simplest way of using it is through the \c graphCopy() function.
662 662
  ///
663 663
  /// This class not only make a copy of a graph, but it can create
664 664
  /// references and cross references between the nodes, edges and arcs of
665 665
  /// the two graphs, and it can copy maps for using with the newly created
666 666
  /// graph.
667 667
  ///
668 668
  /// To make a copy from a graph, first an instance of GraphCopy
669 669
  /// should be created, then the data belongs to the graph should
670 670
  /// assigned to copy. In the end, the \c run() member should be
671 671
  /// called.
672 672
  ///
673 673
  /// The next code copies a graph with several data:
674 674
  ///\code
675 675
  ///  GraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
676 676
  ///  // Create references for the nodes
677 677
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
678 678
  ///  cg.nodeRef(nr);
679 679
  ///  // Create cross references (inverse) for the edges
680 680
  ///  NewGraph::EdgeMap<OrigGraph::Edge> ecr(new_graph);
681 681
  ///  cg.edgeCrossRef(ecr);
682 682
  ///  // Copy an edge map
683 683
  ///  OrigGraph::EdgeMap<double> oemap(orig_graph);
684 684
  ///  NewGraph::EdgeMap<double> nemap(new_graph);
685 685
  ///  cg.edgeMap(oemap, nemap);
686 686
  ///  // Copy a node
687 687
  ///  OrigGraph::Node on;
688 688
  ///  NewGraph::Node nn;
689 689
  ///  cg.node(on, nn);
690 690
  ///  // Execute copying
691 691
  ///  cg.run();
692 692
  ///\endcode
693 693
  template <typename From, typename To>
694 694
  class GraphCopy {
695 695
  private:
696 696

	
697 697
    typedef typename From::Node Node;
698 698
    typedef typename From::NodeIt NodeIt;
699 699
    typedef typename From::Arc Arc;
700 700
    typedef typename From::ArcIt ArcIt;
701 701
    typedef typename From::Edge Edge;
702 702
    typedef typename From::EdgeIt EdgeIt;
703 703

	
704 704
    typedef typename To::Node TNode;
705 705
    typedef typename To::Arc TArc;
706 706
    typedef typename To::Edge TEdge;
707 707

	
708 708
    typedef typename From::template NodeMap<TNode> NodeRefMap;
709 709
    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
710 710

	
711 711
    struct ArcRefMap {
712 712
      ArcRefMap(const From& from, const To& to,
713 713
                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
714 714
        : _from(from), _to(to),
715 715
          _edge_ref(edge_ref), _node_ref(node_ref) {}
716 716

	
717 717
      typedef typename From::Arc Key;
718 718
      typedef typename To::Arc Value;
719 719

	
720 720
      Value operator[](const Key& key) const {
721 721
        bool forward = _from.u(key) != _from.v(key) ?
722 722
          _node_ref[_from.source(key)] ==
723 723
          _to.source(_to.direct(_edge_ref[key], true)) :
724 724
          _from.direction(key);
725 725
        return _to.direct(_edge_ref[key], forward);
726 726
      }
727 727

	
728 728
      const From& _from;
729 729
      const To& _to;
730 730
      const EdgeRefMap& _edge_ref;
731 731
      const NodeRefMap& _node_ref;
732 732
    };
733 733

	
734 734
  public:
735 735

	
736 736
    /// \brief Constructor of GraphCopy.
737 737
    ///
738 738
    /// Constructor of GraphCopy for copying the content of the
739 739
    /// \c from graph into the \c to graph.
740 740
    GraphCopy(const From& from, To& to)
741 741
      : _from(from), _to(to) {}
742 742

	
743 743
    /// \brief Destructor of GraphCopy
744 744
    ///
745 745
    /// Destructor of GraphCopy.
746 746
    ~GraphCopy() {
747 747
      for (int i = 0; i < int(_node_maps.size()); ++i) {
748 748
        delete _node_maps[i];
749 749
      }
750 750
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
751 751
        delete _arc_maps[i];
752 752
      }
753 753
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
754 754
        delete _edge_maps[i];
755 755
      }
756 756
    }
757 757

	
758 758
    /// \brief Copy the node references into the given map.
759 759
    ///
760 760
    /// This function copies the node references into the given map.
761 761
    /// The parameter should be a map, whose key type is the Node type of
762 762
    /// the source graph, while the value type is the Node type of the
763 763
    /// destination graph.
764 764
    template <typename NodeRef>
765 765
    GraphCopy& nodeRef(NodeRef& map) {
766 766
      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
767 767
                           NodeRefMap, NodeRef>(map));
768 768
      return *this;
769 769
    }
770 770

	
771 771
    /// \brief Copy the node cross references into the given map.
772 772
    ///
773 773
    /// This function copies the node cross references (reverse references)
774 774
    /// into the given map. The parameter should be a map, whose key type
775 775
    /// is the Node type of the destination graph, while the value type is
776 776
    /// the Node type of the source graph.
777 777
    template <typename NodeCrossRef>
778 778
    GraphCopy& nodeCrossRef(NodeCrossRef& map) {
779 779
      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
780 780
                           NodeRefMap, NodeCrossRef>(map));
781 781
      return *this;
782 782
    }
783 783

	
784 784
    /// \brief Make a copy of the given node map.
785 785
    ///
786 786
    /// This function makes a copy of the given node map for the newly
787 787
    /// created graph.
788 788
    /// The key type of the new map \c tmap should be the Node type of the
789 789
    /// destination graph, and the key type of the original map \c map
790 790
    /// should be the Node type of the source graph.
791 791
    template <typename FromMap, typename ToMap>
792 792
    GraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
793 793
      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
794 794
                           NodeRefMap, FromMap, ToMap>(map, tmap));
795 795
      return *this;
796 796
    }
797 797

	
798 798
    /// \brief Make a copy of the given node.
799 799
    ///
800 800
    /// This function makes a copy of the given node.
801 801
    GraphCopy& node(const Node& node, TNode& tnode) {
802 802
      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
803 803
                           NodeRefMap, TNode>(node, tnode));
804 804
      return *this;
805 805
    }
806 806

	
807 807
    /// \brief Copy the arc references into the given map.
808 808
    ///
809 809
    /// This function copies the arc references into the given map.
810 810
    /// The parameter should be a map, whose key type is the Arc type of
811 811
    /// the source graph, while the value type is the Arc type of the
812 812
    /// destination graph.
813 813
    template <typename ArcRef>
814 814
    GraphCopy& arcRef(ArcRef& map) {
815 815
      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
816 816
                          ArcRefMap, ArcRef>(map));
817 817
      return *this;
818 818
    }
819 819

	
820 820
    /// \brief Copy the arc cross references into the given map.
821 821
    ///
822 822
    /// This function copies the arc cross references (reverse references)
823 823
    /// into the given map. The parameter should be a map, whose key type
824 824
    /// is the Arc type of the destination graph, while the value type is
825 825
    /// the Arc type of the source graph.
826 826
    template <typename ArcCrossRef>
827 827
    GraphCopy& arcCrossRef(ArcCrossRef& map) {
828 828
      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
829 829
                          ArcRefMap, ArcCrossRef>(map));
830 830
      return *this;
831 831
    }
832 832

	
833 833
    /// \brief Make a copy of the given arc map.
834 834
    ///
835 835
    /// This function makes a copy of the given arc map for the newly
836 836
    /// created graph.
837 837
    /// The key type of the new map \c tmap should be the Arc type of the
838 838
    /// destination graph, and the key type of the original map \c map
839 839
    /// should be the Arc type of the source graph.
840 840
    template <typename FromMap, typename ToMap>
841 841
    GraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
842 842
      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
843 843
                          ArcRefMap, FromMap, ToMap>(map, tmap));
844 844
      return *this;
845 845
    }
846 846

	
847 847
    /// \brief Make a copy of the given arc.
848 848
    ///
849 849
    /// This function makes a copy of the given arc.
850 850
    GraphCopy& arc(const Arc& arc, TArc& tarc) {
851 851
      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
852 852
                          ArcRefMap, TArc>(arc, tarc));
853 853
      return *this;
854 854
    }
855 855

	
856 856
    /// \brief Copy the edge references into the given map.
857 857
    ///
858 858
    /// This function copies the edge references into the given map.
859 859
    /// The parameter should be a map, whose key type is the Edge type of
860 860
    /// the source graph, while the value type is the Edge type of the
861 861
    /// destination graph.
862 862
    template <typename EdgeRef>
863 863
    GraphCopy& edgeRef(EdgeRef& map) {
864 864
      _edge_maps.push_back(new _core_bits::RefCopy<From, Edge,
865 865
                           EdgeRefMap, EdgeRef>(map));
866 866
      return *this;
867 867
    }
868 868

	
869 869
    /// \brief Copy the edge cross references into the given map.
870 870
    ///
871 871
    /// This function copies the edge cross references (reverse references)
872 872
    /// into the given map. The parameter should be a map, whose key type
873 873
    /// is the Edge type of the destination graph, while the value type is
874 874
    /// the Edge type of the source graph.
875 875
    template <typename EdgeCrossRef>
876 876
    GraphCopy& edgeCrossRef(EdgeCrossRef& map) {
877 877
      _edge_maps.push_back(new _core_bits::CrossRefCopy<From,
878 878
                           Edge, EdgeRefMap, EdgeCrossRef>(map));
879 879
      return *this;
880 880
    }
881 881

	
882 882
    /// \brief Make a copy of the given edge map.
883 883
    ///
884 884
    /// This function makes a copy of the given edge map for the newly
885 885
    /// created graph.
886 886
    /// The key type of the new map \c tmap should be the Edge type of the
887 887
    /// destination graph, and the key type of the original map \c map
888 888
    /// should be the Edge type of the source graph.
889 889
    template <typename FromMap, typename ToMap>
890 890
    GraphCopy& edgeMap(const FromMap& map, ToMap& tmap) {
891 891
      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
892 892
                           EdgeRefMap, FromMap, ToMap>(map, tmap));
893 893
      return *this;
894 894
    }
895 895

	
896 896
    /// \brief Make a copy of the given edge.
897 897
    ///
898 898
    /// This function makes a copy of the given edge.
899 899
    GraphCopy& edge(const Edge& edge, TEdge& tedge) {
900 900
      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
901 901
                           EdgeRefMap, TEdge>(edge, tedge));
902 902
      return *this;
903 903
    }
904 904

	
905 905
    /// \brief Execute copying.
906 906
    ///
907 907
    /// This function executes the copying of the graph along with the
908 908
    /// copying of the assigned data.
909 909
    void run() {
910 910
      NodeRefMap nodeRefMap(_from);
911 911
      EdgeRefMap edgeRefMap(_from);
912 912
      ArcRefMap arcRefMap(_from, _to, edgeRefMap, nodeRefMap);
913 913
      _core_bits::GraphCopySelector<To>::
914 914
        copy(_from, _to, nodeRefMap, edgeRefMap);
915 915
      for (int i = 0; i < int(_node_maps.size()); ++i) {
916 916
        _node_maps[i]->copy(_from, nodeRefMap);
917 917
      }
918 918
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
919 919
        _edge_maps[i]->copy(_from, edgeRefMap);
920 920
      }
921 921
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
922 922
        _arc_maps[i]->copy(_from, arcRefMap);
923 923
      }
924 924
    }
925 925

	
926 926
  private:
927 927

	
928 928
    const From& _from;
929 929
    To& _to;
930 930

	
931 931
    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
932 932
      _node_maps;
933 933

	
934 934
    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
935 935
      _arc_maps;
936 936

	
937 937
    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
938 938
      _edge_maps;
939 939

	
940 940
  };
941 941

	
942 942
  /// \brief Copy a graph to another graph.
943 943
  ///
944 944
  /// This function copies a graph to another graph.
945 945
  /// The complete usage of it is detailed in the GraphCopy class,
946 946
  /// but a short example shows a basic work:
947 947
  ///\code
948 948
  /// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run();
949 949
  ///\endcode
950 950
  ///
951 951
  /// After the copy the \c nr map will contain the mapping from the
952 952
  /// nodes of the \c from graph to the nodes of the \c to graph and
953 953
  /// \c ecr will contain the mapping from the edges of the \c to graph
954 954
  /// to the edges of the \c from graph.
955 955
  ///
956 956
  /// \see GraphCopy
957 957
  template <typename From, typename To>
958 958
  GraphCopy<From, To>
959 959
  graphCopy(const From& from, To& to) {
960 960
    return GraphCopy<From, To>(from, to);
961 961
  }
962 962

	
963 963
  namespace _core_bits {
964 964

	
965 965
    template <typename Graph, typename Enable = void>
966 966
    struct FindArcSelector {
967 967
      typedef typename Graph::Node Node;
968 968
      typedef typename Graph::Arc Arc;
969 969
      static Arc find(const Graph &g, Node u, Node v, Arc e) {
970 970
        if (e == INVALID) {
971 971
          g.firstOut(e, u);
972 972
        } else {
973 973
          g.nextOut(e);
974 974
        }
975 975
        while (e != INVALID && g.target(e) != v) {
976 976
          g.nextOut(e);
977 977
        }
978 978
        return e;
979 979
      }
980 980
    };
981 981

	
982 982
    template <typename Graph>
983 983
    struct FindArcSelector<
984 984
      Graph,
985 985
      typename enable_if<typename Graph::FindArcTag, void>::type>
986 986
    {
987 987
      typedef typename Graph::Node Node;
988 988
      typedef typename Graph::Arc Arc;
989 989
      static Arc find(const Graph &g, Node u, Node v, Arc prev) {
990 990
        return g.findArc(u, v, prev);
991 991
      }
992 992
    };
993 993
  }
994 994

	
995 995
  /// \brief Find an arc between two nodes of a digraph.
996 996
  ///
997 997
  /// This function finds an arc from node \c u to node \c v in the
998 998
  /// digraph \c g.
999 999
  ///
1000 1000
  /// If \c prev is \ref INVALID (this is the default value), then
1001 1001
  /// it finds the first arc from \c u to \c v. Otherwise it looks for
1002 1002
  /// the next arc from \c u to \c v after \c prev.
1003 1003
  /// \return The found arc or \ref INVALID if there is no such an arc.
1004 1004
  ///
1005 1005
  /// Thus you can iterate through each arc from \c u to \c v as it follows.
1006 1006
  ///\code
1007 1007
  /// for(Arc e = findArc(g,u,v); e != INVALID; e = findArc(g,u,v,e)) {
1008 1008
  ///   ...
1009 1009
  /// }
1010 1010
  ///\endcode
1011 1011
  ///
1012 1012
  /// \note \ref ConArcIt provides iterator interface for the same
1013 1013
  /// functionality.
1014 1014
  ///
1015 1015
  ///\sa ConArcIt
1016 1016
  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1017 1017
  template <typename Graph>
1018 1018
  inline typename Graph::Arc
1019 1019
  findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1020 1020
          typename Graph::Arc prev = INVALID) {
1021 1021
    return _core_bits::FindArcSelector<Graph>::find(g, u, v, prev);
1022 1022
  }
1023 1023

	
1024 1024
  /// \brief Iterator for iterating on parallel arcs connecting the same nodes.
1025 1025
  ///
1026 1026
  /// Iterator for iterating on parallel arcs connecting the same nodes. It is
1027 1027
  /// a higher level interface for the \ref findArc() function. You can
1028 1028
  /// use it the following way:
1029 1029
  ///\code
1030 1030
  /// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) {
1031 1031
  ///   ...
1032 1032
  /// }
1033 1033
  ///\endcode
1034 1034
  ///
1035 1035
  ///\sa findArc()
1036 1036
  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1037 1037
  template <typename GR>
1038 1038
  class ConArcIt : public GR::Arc {
1039 1039
    typedef typename GR::Arc Parent;
1040 1040

	
1041 1041
  public:
1042 1042

	
1043 1043
    typedef typename GR::Arc Arc;
1044 1044
    typedef typename GR::Node Node;
1045 1045

	
1046 1046
    /// \brief Constructor.
1047 1047
    ///
1048 1048
    /// Construct a new ConArcIt iterating on the arcs that
1049 1049
    /// connects nodes \c u and \c v.
1050 1050
    ConArcIt(const GR& g, Node u, Node v) : _graph(g) {
1051 1051
      Parent::operator=(findArc(_graph, u, v));
1052 1052
    }
1053 1053

	
1054 1054
    /// \brief Constructor.
1055 1055
    ///
1056 1056
    /// Construct a new ConArcIt that continues the iterating from arc \c a.
1057 1057
    ConArcIt(const GR& g, Arc a) : Parent(a), _graph(g) {}
1058 1058

	
1059 1059
    /// \brief Increment operator.
1060 1060
    ///
1061 1061
    /// It increments the iterator and gives back the next arc.
1062 1062
    ConArcIt& operator++() {
1063 1063
      Parent::operator=(findArc(_graph, _graph.source(*this),
1064 1064
                                _graph.target(*this), *this));
1065 1065
      return *this;
1066 1066
    }
1067 1067
  private:
1068 1068
    const GR& _graph;
1069 1069
  };
1070 1070

	
1071 1071
  namespace _core_bits {
1072 1072

	
1073 1073
    template <typename Graph, typename Enable = void>
1074 1074
    struct FindEdgeSelector {
1075 1075
      typedef typename Graph::Node Node;
1076 1076
      typedef typename Graph::Edge Edge;
1077 1077
      static Edge find(const Graph &g, Node u, Node v, Edge e) {
1078 1078
        bool b;
1079 1079
        if (u != v) {
1080 1080
          if (e == INVALID) {
1081 1081
            g.firstInc(e, b, u);
1082 1082
          } else {
1083 1083
            b = g.u(e) == u;
1084 1084
            g.nextInc(e, b);
1085 1085
          }
1086 1086
          while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) {
1087 1087
            g.nextInc(e, b);
1088 1088
          }
1089 1089
        } else {
1090 1090
          if (e == INVALID) {
1091 1091
            g.firstInc(e, b, u);
1092 1092
          } else {
1093 1093
            b = true;
1094 1094
            g.nextInc(e, b);
1095 1095
          }
1096 1096
          while (e != INVALID && (!b || g.v(e) != v)) {
1097 1097
            g.nextInc(e, b);
1098 1098
          }
1099 1099
        }
1100 1100
        return e;
1101 1101
      }
1102 1102
    };
1103 1103

	
1104 1104
    template <typename Graph>
1105 1105
    struct FindEdgeSelector<
1106 1106
      Graph,
1107 1107
      typename enable_if<typename Graph::FindEdgeTag, void>::type>
1108 1108
    {
1109 1109
      typedef typename Graph::Node Node;
1110 1110
      typedef typename Graph::Edge Edge;
1111 1111
      static Edge find(const Graph &g, Node u, Node v, Edge prev) {
1112 1112
        return g.findEdge(u, v, prev);
1113 1113
      }
1114 1114
    };
1115 1115
  }
1116 1116

	
1117 1117
  /// \brief Find an edge between two nodes of a graph.
1118 1118
  ///
1119 1119
  /// This function finds an edge from node \c u to node \c v in graph \c g.
1120 1120
  /// If node \c u and node \c v is equal then each loop edge
1121 1121
  /// will be enumerated once.
1122 1122
  ///
1123 1123
  /// If \c prev is \ref INVALID (this is the default value), then
1124 1124
  /// it finds the first edge from \c u to \c v. Otherwise it looks for
1125 1125
  /// the next edge from \c u to \c v after \c prev.
1126 1126
  /// \return The found edge or \ref INVALID if there is no such an edge.
1127 1127
  ///
1128 1128
  /// Thus you can iterate through each edge between \c u and \c v
1129 1129
  /// as it follows.
1130 1130
  ///\code
1131 1131
  /// for(Edge e = findEdge(g,u,v); e != INVALID; e = findEdge(g,u,v,e)) {
1132 1132
  ///   ...
1133 1133
  /// }
1134 1134
  ///\endcode
1135 1135
  ///
1136 1136
  /// \note \ref ConEdgeIt provides iterator interface for the same
1137 1137
  /// functionality.
1138 1138
  ///
1139 1139
  ///\sa ConEdgeIt
1140 1140
  template <typename Graph>
1141 1141
  inline typename Graph::Edge
1142 1142
  findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1143 1143
            typename Graph::Edge p = INVALID) {
1144 1144
    return _core_bits::FindEdgeSelector<Graph>::find(g, u, v, p);
1145 1145
  }
1146 1146

	
1147 1147
  /// \brief Iterator for iterating on parallel edges connecting the same nodes.
1148 1148
  ///
1149 1149
  /// Iterator for iterating on parallel edges connecting the same nodes.
1150 1150
  /// It is a higher level interface for the findEdge() function. You can
1151 1151
  /// use it the following way:
1152 1152
  ///\code
1153 1153
  /// for (ConEdgeIt<Graph> it(g, u, v); it != INVALID; ++it) {
1154 1154
  ///   ...
1155 1155
  /// }
1156 1156
  ///\endcode
1157 1157
  ///
1158 1158
  ///\sa findEdge()
1159 1159
  template <typename GR>
1160 1160
  class ConEdgeIt : public GR::Edge {
1161 1161
    typedef typename GR::Edge Parent;
1162 1162

	
1163 1163
  public:
1164 1164

	
1165 1165
    typedef typename GR::Edge Edge;
1166 1166
    typedef typename GR::Node Node;
1167 1167

	
1168 1168
    /// \brief Constructor.
1169 1169
    ///
1170 1170
    /// Construct a new ConEdgeIt iterating on the edges that
1171 1171
    /// connects nodes \c u and \c v.
1172 1172
    ConEdgeIt(const GR& g, Node u, Node v) : _graph(g), _u(u), _v(v) {
1173 1173
      Parent::operator=(findEdge(_graph, _u, _v));
1174 1174
    }
1175 1175

	
1176 1176
    /// \brief Constructor.
1177 1177
    ///
1178 1178
    /// Construct a new ConEdgeIt that continues iterating from edge \c e.
1179 1179
    ConEdgeIt(const GR& g, Edge e) : Parent(e), _graph(g) {}
1180 1180

	
1181 1181
    /// \brief Increment operator.
1182 1182
    ///
1183 1183
    /// It increments the iterator and gives back the next edge.
1184 1184
    ConEdgeIt& operator++() {
1185 1185
      Parent::operator=(findEdge(_graph, _u, _v, *this));
1186 1186
      return *this;
1187 1187
    }
1188 1188
  private:
1189 1189
    const GR& _graph;
1190 1190
    Node _u, _v;
1191 1191
  };
1192 1192

	
1193 1193

	
1194 1194
  ///Dynamic arc look-up between given endpoints.
1195 1195

	
1196 1196
  ///Using this class, you can find an arc in a digraph from a given
1197 1197
  ///source to a given target in amortized time <em>O</em>(log<em>d</em>),
1198 1198
  ///where <em>d</em> is the out-degree of the source node.
1199 1199
  ///
1200 1200
  ///It is possible to find \e all parallel arcs between two nodes with
1201 1201
  ///the \c operator() member.
1202 1202
  ///
1203 1203
  ///This is a dynamic data structure. Consider to use \ref ArcLookUp or
1204 1204
  ///\ref AllArcLookUp if your digraph is not changed so frequently.
1205 1205
  ///
1206 1206
  ///This class uses a self-adjusting binary search tree, the Splay tree
1207 1207
  ///of Sleator and Tarjan to guarantee the logarithmic amortized
1208 1208
  ///time bound for arc look-ups. This class also guarantees the
1209 1209
  ///optimal time bound in a constant factor for any distribution of
1210 1210
  ///queries.
1211 1211
  ///
1212 1212
  ///\tparam GR The type of the underlying digraph.
1213 1213
  ///
1214 1214
  ///\sa ArcLookUp
1215 1215
  ///\sa AllArcLookUp
1216 1216
  template <typename GR>
1217 1217
  class DynArcLookUp
1218 1218
    : protected ItemSetTraits<GR, typename GR::Arc>::ItemNotifier::ObserverBase
1219 1219
  {
1220 1220
    typedef typename ItemSetTraits<GR, typename GR::Arc>
1221 1221
    ::ItemNotifier::ObserverBase Parent;
1222 1222

	
1223 1223
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1224 1224

	
1225 1225
  public:
1226 1226

	
1227 1227
    /// The Digraph type
1228 1228
    typedef GR Digraph;
1229 1229

	
1230 1230
  protected:
1231 1231

	
1232 1232
    class AutoNodeMap : public ItemSetTraits<GR, Node>::template Map<Arc>::Type {
1233 1233
      typedef typename ItemSetTraits<GR, Node>::template Map<Arc>::Type Parent;
1234 1234

	
1235 1235
    public:
1236 1236

	
1237 1237
      AutoNodeMap(const GR& digraph) : Parent(digraph, INVALID) {}
1238 1238

	
1239 1239
      virtual void add(const Node& node) {
1240 1240
        Parent::add(node);
1241 1241
        Parent::set(node, INVALID);
1242 1242
      }
1243 1243

	
1244 1244
      virtual void add(const std::vector<Node>& nodes) {
1245 1245
        Parent::add(nodes);
1246 1246
        for (int i = 0; i < int(nodes.size()); ++i) {
1247 1247
          Parent::set(nodes[i], INVALID);
1248 1248
        }
1249 1249
      }
1250 1250

	
1251 1251
      virtual void build() {
1252 1252
        Parent::build();
1253 1253
        Node it;
1254 1254
        typename Parent::Notifier* nf = Parent::notifier();
1255 1255
        for (nf->first(it); it != INVALID; nf->next(it)) {
1256 1256
          Parent::set(it, INVALID);
1257 1257
        }
1258 1258
      }
1259 1259
    };
1260 1260

	
1261 1261
    class ArcLess {
1262 1262
      const Digraph &g;
1263 1263
    public:
1264 1264
      ArcLess(const Digraph &_g) : g(_g) {}
1265 1265
      bool operator()(Arc a,Arc b) const
1266 1266
      {
1267 1267
        return g.target(a)<g.target(b);
1268 1268
      }
1269 1269
    };
1270 1270

	
1271 1271
  protected: 
1272 1272

	
1273 1273
    const Digraph &_g;
1274 1274
    AutoNodeMap _head;
1275 1275
    typename Digraph::template ArcMap<Arc> _parent;
1276 1276
    typename Digraph::template ArcMap<Arc> _left;
1277 1277
    typename Digraph::template ArcMap<Arc> _right;
1278 1278

	
1279 1279
  public:
1280 1280

	
1281 1281
    ///Constructor
1282 1282

	
1283 1283
    ///Constructor.
1284 1284
    ///
1285 1285
    ///It builds up the search database.
1286 1286
    DynArcLookUp(const Digraph &g)
1287 1287
      : _g(g),_head(g),_parent(g),_left(g),_right(g)
1288 1288
    {
1289 1289
      Parent::attach(_g.notifier(typename Digraph::Arc()));
1290 1290
      refresh();
1291 1291
    }
1292 1292

	
1293 1293
  protected:
1294 1294

	
1295 1295
    virtual void add(const Arc& arc) {
1296 1296
      insert(arc);
1297 1297
    }
1298 1298

	
1299 1299
    virtual void add(const std::vector<Arc>& arcs) {
1300 1300
      for (int i = 0; i < int(arcs.size()); ++i) {
1301 1301
        insert(arcs[i]);
1302 1302
      }
1303 1303
    }
1304 1304

	
1305 1305
    virtual void erase(const Arc& arc) {
1306 1306
      remove(arc);
1307 1307
    }
1308 1308

	
1309 1309
    virtual void erase(const std::vector<Arc>& arcs) {
1310 1310
      for (int i = 0; i < int(arcs.size()); ++i) {
1311 1311
        remove(arcs[i]);
1312 1312
      }
1313 1313
    }
1314 1314

	
1315 1315
    virtual void build() {
1316 1316
      refresh();
1317 1317
    }
1318 1318

	
1319 1319
    virtual void clear() {
1320 1320
      for(NodeIt n(_g);n!=INVALID;++n) {
1321 1321
        _head[n] = INVALID;
1322 1322
      }
1323 1323
    }
1324 1324

	
1325 1325
    void insert(Arc arc) {
1326 1326
      Node s = _g.source(arc);
1327 1327
      Node t = _g.target(arc);
1328 1328
      _left[arc] = INVALID;
1329 1329
      _right[arc] = INVALID;
1330 1330

	
1331 1331
      Arc e = _head[s];
1332 1332
      if (e == INVALID) {
1333 1333
        _head[s] = arc;
1334 1334
        _parent[arc] = INVALID;
1335 1335
        return;
1336 1336
      }
1337 1337
      while (true) {
1338 1338
        if (t < _g.target(e)) {
1339 1339
          if (_left[e] == INVALID) {
1340 1340
            _left[e] = arc;
1341 1341
            _parent[arc] = e;
1342 1342
            splay(arc);
1343 1343
            return;
1344 1344
          } else {
1345 1345
            e = _left[e];
1346 1346
          }
1347 1347
        } else {
1348 1348
          if (_right[e] == INVALID) {
1349 1349
            _right[e] = arc;
1350 1350
            _parent[arc] = e;
1351 1351
            splay(arc);
1352 1352
            return;
1353 1353
          } else {
1354 1354
            e = _right[e];
1355 1355
          }
1356 1356
        }
1357 1357
      }
1358 1358
    }
1359 1359

	
1360 1360
    void remove(Arc arc) {
1361 1361
      if (_left[arc] == INVALID) {
1362 1362
        if (_right[arc] != INVALID) {
1363 1363
          _parent[_right[arc]] = _parent[arc];
1364 1364
        }
1365 1365
        if (_parent[arc] != INVALID) {
1366 1366
          if (_left[_parent[arc]] == arc) {
1367 1367
            _left[_parent[arc]] = _right[arc];
1368 1368
          } else {
1369 1369
            _right[_parent[arc]] = _right[arc];
1370 1370
          }
1371 1371
        } else {
1372 1372
          _head[_g.source(arc)] = _right[arc];
1373 1373
        }
1374 1374
      } else if (_right[arc] == INVALID) {
1375 1375
        _parent[_left[arc]] = _parent[arc];
1376 1376
        if (_parent[arc] != INVALID) {
1377 1377
          if (_left[_parent[arc]] == arc) {
1378 1378
            _left[_parent[arc]] = _left[arc];
1379 1379
          } else {
1380 1380
            _right[_parent[arc]] = _left[arc];
1381 1381
          }
1382 1382
        } else {
1383 1383
          _head[_g.source(arc)] = _left[arc];
1384 1384
        }
1385 1385
      } else {
1386 1386
        Arc e = _left[arc];
1387 1387
        if (_right[e] != INVALID) {
1388 1388
          e = _right[e];
1389 1389
          while (_right[e] != INVALID) {
1390 1390
            e = _right[e];
1391 1391
          }
1392 1392
          Arc s = _parent[e];
1393 1393
          _right[_parent[e]] = _left[e];
1394 1394
          if (_left[e] != INVALID) {
1395 1395
            _parent[_left[e]] = _parent[e];
1396 1396
          }
1397 1397

	
1398 1398
          _left[e] = _left[arc];
1399 1399
          _parent[_left[arc]] = e;
1400 1400
          _right[e] = _right[arc];
1401 1401
          _parent[_right[arc]] = e;
1402 1402

	
1403 1403
          _parent[e] = _parent[arc];
1404 1404
          if (_parent[arc] != INVALID) {
1405 1405
            if (_left[_parent[arc]] == arc) {
1406 1406
              _left[_parent[arc]] = e;
1407 1407
            } else {
1408 1408
              _right[_parent[arc]] = e;
1409 1409
            }
1410 1410
          }
1411 1411
          splay(s);
1412 1412
        } else {
1413 1413
          _right[e] = _right[arc];
1414 1414
          _parent[_right[arc]] = e;
1415 1415
          _parent[e] = _parent[arc];
1416 1416

	
1417 1417
          if (_parent[arc] != INVALID) {
1418 1418
            if (_left[_parent[arc]] == arc) {
1419 1419
              _left[_parent[arc]] = e;
1420 1420
            } else {
1421 1421
              _right[_parent[arc]] = e;
1422 1422
            }
1423 1423
          } else {
1424 1424
            _head[_g.source(arc)] = e;
1425 1425
          }
1426 1426
        }
1427 1427
      }
1428 1428
    }
1429 1429

	
1430 1430
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1431 1431
    {
1432 1432
      int m=(a+b)/2;
1433 1433
      Arc me=v[m];
1434 1434
      if (a < m) {
1435 1435
        Arc left = refreshRec(v,a,m-1);
1436 1436
        _left[me] = left;
1437 1437
        _parent[left] = me;
1438 1438
      } else {
1439 1439
        _left[me] = INVALID;
1440 1440
      }
1441 1441
      if (m < b) {
1442 1442
        Arc right = refreshRec(v,m+1,b);
1443 1443
        _right[me] = right;
1444 1444
        _parent[right] = me;
1445 1445
      } else {
1446 1446
        _right[me] = INVALID;
1447 1447
      }
1448 1448
      return me;
1449 1449
    }
1450 1450

	
1451 1451
    void refresh() {
1452 1452
      for(NodeIt n(_g);n!=INVALID;++n) {
1453 1453
        std::vector<Arc> v;
1454 1454
        for(OutArcIt a(_g,n);a!=INVALID;++a) v.push_back(a);
1455 1455
        if (!v.empty()) {
1456 1456
          std::sort(v.begin(),v.end(),ArcLess(_g));
1457 1457
          Arc head = refreshRec(v,0,v.size()-1);
1458 1458
          _head[n] = head;
1459 1459
          _parent[head] = INVALID;
1460 1460
        }
1461 1461
        else _head[n] = INVALID;
1462 1462
      }
1463 1463
    }
1464 1464

	
1465 1465
    void zig(Arc v) {
1466 1466
      Arc w = _parent[v];
1467 1467
      _parent[v] = _parent[w];
1468 1468
      _parent[w] = v;
1469 1469
      _left[w] = _right[v];
1470 1470
      _right[v] = w;
1471 1471
      if (_parent[v] != INVALID) {
1472 1472
        if (_right[_parent[v]] == w) {
1473 1473
          _right[_parent[v]] = v;
1474 1474
        } else {
1475 1475
          _left[_parent[v]] = v;
1476 1476
        }
1477 1477
      }
1478 1478
      if (_left[w] != INVALID){
1479 1479
        _parent[_left[w]] = w;
1480 1480
      }
1481 1481
    }
1482 1482

	
1483 1483
    void zag(Arc v) {
1484 1484
      Arc w = _parent[v];
1485 1485
      _parent[v] = _parent[w];
1486 1486
      _parent[w] = v;
1487 1487
      _right[w] = _left[v];
1488 1488
      _left[v] = w;
1489 1489
      if (_parent[v] != INVALID){
1490 1490
        if (_left[_parent[v]] == w) {
1491 1491
          _left[_parent[v]] = v;
1492 1492
        } else {
1493 1493
          _right[_parent[v]] = v;
1494 1494
        }
1495 1495
      }
1496 1496
      if (_right[w] != INVALID){
1497 1497
        _parent[_right[w]] = w;
1498 1498
      }
1499 1499
    }
1500 1500

	
1501 1501
    void splay(Arc v) {
1502 1502
      while (_parent[v] != INVALID) {
1503 1503
        if (v == _left[_parent[v]]) {
1504 1504
          if (_parent[_parent[v]] == INVALID) {
1505 1505
            zig(v);
1506 1506
          } else {
1507 1507
            if (_parent[v] == _left[_parent[_parent[v]]]) {
1508 1508
              zig(_parent[v]);
1509 1509
              zig(v);
1510 1510
            } else {
1511 1511
              zig(v);
1512 1512
              zag(v);
1513 1513
            }
1514 1514
          }
1515 1515
        } else {
1516 1516
          if (_parent[_parent[v]] == INVALID) {
1517 1517
            zag(v);
1518 1518
          } else {
1519 1519
            if (_parent[v] == _left[_parent[_parent[v]]]) {
1520 1520
              zag(v);
1521 1521
              zig(v);
1522 1522
            } else {
1523 1523
              zag(_parent[v]);
1524 1524
              zag(v);
1525 1525
            }
1526 1526
          }
1527 1527
        }
1528 1528
      }
1529 1529
      _head[_g.source(v)] = v;
1530 1530
    }
1531 1531

	
1532 1532

	
1533 1533
  public:
1534 1534

	
1535 1535
    ///Find an arc between two nodes.
1536 1536

	
1537 1537
    ///Find an arc between two nodes.
1538 1538
    ///\param s The source node.
1539 1539
    ///\param t The target node.
1540 1540
    ///\param p The previous arc between \c s and \c t. It it is INVALID or
1541 1541
    ///not given, the operator finds the first appropriate arc.
1542 1542
    ///\return An arc from \c s to \c t after \c p or
1543 1543
    ///\ref INVALID if there is no more.
1544 1544
    ///
1545 1545
    ///For example, you can count the number of arcs from \c u to \c v in the
1546 1546
    ///following way.
1547 1547
    ///\code
1548 1548
    ///DynArcLookUp<ListDigraph> ae(g);
1549 1549
    ///...
1550 1550
    ///int n = 0;
1551 1551
    ///for(Arc a = ae(u,v); a != INVALID; a = ae(u,v,a)) n++;
1552 1552
    ///\endcode
1553 1553
    ///
1554 1554
    ///Finding the arcs take at most <em>O</em>(log<em>d</em>)
1555 1555
    ///amortized time, specifically, the time complexity of the lookups
1556 1556
    ///is equal to the optimal search tree implementation for the
1557 1557
    ///current query distribution in a constant factor.
1558 1558
    ///
1559 1559
    ///\note This is a dynamic data structure, therefore the data
1560 1560
    ///structure is updated after each graph alteration. Thus although
1561 1561
    ///this data structure is theoretically faster than \ref ArcLookUp
1562 1562
    ///and \ref AllArcLookUp, it often provides worse performance than
1563 1563
    ///them.
1564 1564
    Arc operator()(Node s, Node t, Arc p = INVALID) const  {
1565 1565
      if (p == INVALID) {
1566 1566
        Arc a = _head[s];
1567 1567
        if (a == INVALID) return INVALID;
1568 1568
        Arc r = INVALID;
1569 1569
        while (true) {
1570 1570
          if (_g.target(a) < t) {
1571 1571
            if (_right[a] == INVALID) {
1572 1572
              const_cast<DynArcLookUp&>(*this).splay(a);
1573 1573
              return r;
1574 1574
            } else {
1575 1575
              a = _right[a];
1576 1576
            }
1577 1577
          } else {
1578 1578
            if (_g.target(a) == t) {
1579 1579
              r = a;
1580 1580
            }
1581 1581
            if (_left[a] == INVALID) {
1582 1582
              const_cast<DynArcLookUp&>(*this).splay(a);
1583 1583
              return r;
1584 1584
            } else {
1585 1585
              a = _left[a];
1586 1586
            }
1587 1587
          }
1588 1588
        }
1589 1589
      } else {
1590 1590
        Arc a = p;
1591 1591
        if (_right[a] != INVALID) {
1592 1592
          a = _right[a];
1593 1593
          while (_left[a] != INVALID) {
1594 1594
            a = _left[a];
1595 1595
          }
1596 1596
          const_cast<DynArcLookUp&>(*this).splay(a);
1597 1597
        } else {
1598 1598
          while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
1599 1599
            a = _parent[a];
1600 1600
          }
1601 1601
          if (_parent[a] == INVALID) {
1602 1602
            return INVALID;
1603 1603
          } else {
1604 1604
            a = _parent[a];
1605 1605
            const_cast<DynArcLookUp&>(*this).splay(a);
1606 1606
          }
1607 1607
        }
1608 1608
        if (_g.target(a) == t) return a;
1609 1609
        else return INVALID;
1610 1610
      }
1611 1611
    }
1612 1612

	
1613 1613
  };
1614 1614

	
1615 1615
  ///Fast arc look-up between given endpoints.
1616 1616

	
1617 1617
  ///Using this class, you can find an arc in a digraph from a given
1618 1618
  ///source to a given target in time <em>O</em>(log<em>d</em>),
1619 1619
  ///where <em>d</em> is the out-degree of the source node.
1620 1620
  ///
1621 1621
  ///It is not possible to find \e all parallel arcs between two nodes.
1622 1622
  ///Use \ref AllArcLookUp for this purpose.
1623 1623
  ///
1624 1624
  ///\warning This class is static, so you should call refresh() (or at
1625 1625
  ///least refresh(Node)) to refresh this data structure whenever the
1626 1626
  ///digraph changes. This is a time consuming (superlinearly proportional
1627 1627
  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
1628 1628
  ///
1629 1629
  ///\tparam GR The type of the underlying digraph.
1630 1630
  ///
1631 1631
  ///\sa DynArcLookUp
1632 1632
  ///\sa AllArcLookUp
1633 1633
  template<class GR>
1634 1634
  class ArcLookUp
1635 1635
  {
1636 1636
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1637 1637

	
1638 1638
  public:
1639 1639

	
1640 1640
    /// The Digraph type
1641 1641
    typedef GR Digraph;
1642 1642

	
1643 1643
  protected:
1644 1644
    const Digraph &_g;
1645 1645
    typename Digraph::template NodeMap<Arc> _head;
1646 1646
    typename Digraph::template ArcMap<Arc> _left;
1647 1647
    typename Digraph::template ArcMap<Arc> _right;
1648 1648

	
1649 1649
    class ArcLess {
1650 1650
      const Digraph &g;
1651 1651
    public:
1652 1652
      ArcLess(const Digraph &_g) : g(_g) {}
1653 1653
      bool operator()(Arc a,Arc b) const
1654 1654
      {
1655 1655
        return g.target(a)<g.target(b);
1656 1656
      }
1657 1657
    };
1658 1658

	
1659 1659
  public:
1660 1660

	
1661 1661
    ///Constructor
1662 1662

	
1663 1663
    ///Constructor.
1664 1664
    ///
1665 1665
    ///It builds up the search database, which remains valid until the digraph
1666 1666
    ///changes.
1667 1667
    ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();}
1668 1668

	
1669 1669
  private:
1670 1670
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1671 1671
    {
1672 1672
      int m=(a+b)/2;
1673 1673
      Arc me=v[m];
1674 1674
      _left[me] = a<m?refreshRec(v,a,m-1):INVALID;
1675 1675
      _right[me] = m<b?refreshRec(v,m+1,b):INVALID;
1676 1676
      return me;
1677 1677
    }
1678 1678
  public:
1679 1679
    ///Refresh the search data structure at a node.
1680 1680

	
1681 1681
    ///Build up the search database of node \c n.
1682 1682
    ///
1683 1683
    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em>
1684 1684
    ///is the number of the outgoing arcs of \c n.
1685 1685
    void refresh(Node n)
1686 1686
    {
1687 1687
      std::vector<Arc> v;
1688 1688
      for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
1689 1689
      if(v.size()) {
1690 1690
        std::sort(v.begin(),v.end(),ArcLess(_g));
1691 1691
        _head[n]=refreshRec(v,0,v.size()-1);
1692 1692
      }
1693 1693
      else _head[n]=INVALID;
1694 1694
    }
1695 1695
    ///Refresh the full data structure.
1696 1696

	
1697 1697
    ///Build up the full search database. In fact, it simply calls
1698 1698
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1699 1699
    ///
1700 1700
    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
1701 1701
    ///the number of the arcs in the digraph and <em>D</em> is the maximum
1702 1702
    ///out-degree of the digraph.
1703 1703
    void refresh()
1704 1704
    {
1705 1705
      for(NodeIt n(_g);n!=INVALID;++n) refresh(n);
1706 1706
    }
1707 1707

	
1708 1708
    ///Find an arc between two nodes.
1709 1709

	
1710 1710
    ///Find an arc between two nodes in time <em>O</em>(log<em>d</em>),
1711 1711
    ///where <em>d</em> is the number of outgoing arcs of \c s.
1712 1712
    ///\param s The source node.
1713 1713
    ///\param t The target node.
1714 1714
    ///\return An arc from \c s to \c t if there exists,
1715 1715
    ///\ref INVALID otherwise.
1716 1716
    ///
1717 1717
    ///\warning If you change the digraph, refresh() must be called before using
1718 1718
    ///this operator. If you change the outgoing arcs of
1719 1719
    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
1720 1720
    Arc operator()(Node s, Node t) const
1721 1721
    {
1722 1722
      Arc e;
1723 1723
      for(e=_head[s];
1724 1724
          e!=INVALID&&_g.target(e)!=t;
1725 1725
          e = t < _g.target(e)?_left[e]:_right[e]) ;
1726 1726
      return e;
1727 1727
    }
1728 1728

	
1729 1729
  };
1730 1730

	
1731 1731
  ///Fast look-up of all arcs between given endpoints.
1732 1732

	
1733 1733
  ///This class is the same as \ref ArcLookUp, with the addition
1734 1734
  ///that it makes it possible to find all parallel arcs between given
1735 1735
  ///endpoints.
1736 1736
  ///
1737 1737
  ///\warning This class is static, so you should call refresh() (or at
1738 1738
  ///least refresh(Node)) to refresh this data structure whenever the
1739 1739
  ///digraph changes. This is a time consuming (superlinearly proportional
1740 1740
  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
1741 1741
  ///
1742 1742
  ///\tparam GR The type of the underlying digraph.
1743 1743
  ///
1744 1744
  ///\sa DynArcLookUp
1745 1745
  ///\sa ArcLookUp
1746 1746
  template<class GR>
1747 1747
  class AllArcLookUp : public ArcLookUp<GR>
1748 1748
  {
1749 1749
    using ArcLookUp<GR>::_g;
1750 1750
    using ArcLookUp<GR>::_right;
1751 1751
    using ArcLookUp<GR>::_left;
1752 1752
    using ArcLookUp<GR>::_head;
1753 1753

	
1754 1754
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
1755 1755

	
1756 1756
    typename GR::template ArcMap<Arc> _next;
1757 1757

	
1758 1758
    Arc refreshNext(Arc head,Arc next=INVALID)
1759 1759
    {
1760 1760
      if(head==INVALID) return next;
1761 1761
      else {
1762 1762
        next=refreshNext(_right[head],next);
1763 1763
        _next[head]=( next!=INVALID && _g.target(next)==_g.target(head))
1764 1764
          ? next : INVALID;
1765 1765
        return refreshNext(_left[head],head);
1766 1766
      }
1767 1767
    }
1768 1768

	
1769 1769
    void refreshNext()
1770 1770
    {
1771 1771
      for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]);
1772 1772
    }
1773 1773

	
1774 1774
  public:
1775 1775

	
1776 1776
    /// The Digraph type
1777 1777
    typedef GR Digraph;
1778 1778

	
1779 1779
    ///Constructor
1780 1780

	
1781 1781
    ///Constructor.
1782 1782
    ///
1783 1783
    ///It builds up the search database, which remains valid until the digraph
1784 1784
    ///changes.
1785 1785
    AllArcLookUp(const Digraph &g) : ArcLookUp<GR>(g), _next(g) {refreshNext();}
1786 1786

	
1787 1787
    ///Refresh the data structure at a node.
1788 1788

	
1789 1789
    ///Build up the search database of node \c n.
1790 1790
    ///
1791 1791
    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em> is
1792 1792
    ///the number of the outgoing arcs of \c n.
1793 1793
    void refresh(Node n)
1794 1794
    {
1795 1795
      ArcLookUp<GR>::refresh(n);
1796 1796
      refreshNext(_head[n]);
1797 1797
    }
1798 1798

	
1799 1799
    ///Refresh the full data structure.
1800 1800

	
1801 1801
    ///Build up the full search database. In fact, it simply calls
1802 1802
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1803 1803
    ///
1804 1804
    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
1805 1805
    ///the number of the arcs in the digraph and <em>D</em> is the maximum
1806 1806
    ///out-degree of the digraph.
1807 1807
    void refresh()
1808 1808
    {
1809 1809
      for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]);
1810 1810
    }
1811 1811

	
1812 1812
    ///Find an arc between two nodes.
1813 1813

	
1814 1814
    ///Find an arc between two nodes.
1815 1815
    ///\param s The source node.
1816 1816
    ///\param t The target node.
1817 1817
    ///\param prev The previous arc between \c s and \c t. It it is INVALID or
1818 1818
    ///not given, the operator finds the first appropriate arc.
1819 1819
    ///\return An arc from \c s to \c t after \c prev or
1820 1820
    ///\ref INVALID if there is no more.
1821 1821
    ///
1822 1822
    ///For example, you can count the number of arcs from \c u to \c v in the
1823 1823
    ///following way.
1824 1824
    ///\code
1825 1825
    ///AllArcLookUp<ListDigraph> ae(g);
1826 1826
    ///...
1827 1827
    ///int n = 0;
1828 1828
    ///for(Arc a = ae(u,v); a != INVALID; a=ae(u,v,a)) n++;
1829 1829
    ///\endcode
1830 1830
    ///
1831 1831
    ///Finding the first arc take <em>O</em>(log<em>d</em>) time,
1832 1832
    ///where <em>d</em> is the number of outgoing arcs of \c s. Then the
1833 1833
    ///consecutive arcs are found in constant time.
1834 1834
    ///
1835 1835
    ///\warning If you change the digraph, refresh() must be called before using
1836 1836
    ///this operator. If you change the outgoing arcs of
1837 1837
    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
1838 1838
    ///
1839 1839
#ifdef DOXYGEN
1840 1840
    Arc operator()(Node s, Node t, Arc prev=INVALID) const {}
1841 1841
#else
1842 1842
    using ArcLookUp<GR>::operator() ;
1843 1843
    Arc operator()(Node s, Node t, Arc prev) const
1844 1844
    {
1845 1845
      return prev==INVALID?(*this)(s,t):_next[prev];
1846 1846
    }
1847 1847
#endif
1848 1848

	
1849 1849
  };
1850 1850

	
1851 1851
  /// @}
1852 1852

	
1853 1853
} //namespace lemon
1854 1854

	
1855 1855
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_NETWORK_SIMPLEX_H
20 20
#define LEMON_NETWORK_SIMPLEX_H
21 21

	
22 22
/// \ingroup min_cost_flow
23 23
///
24 24
/// \file
25 25
/// \brief Network Simplex algorithm for finding a minimum cost flow.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <algorithm>
30 30

	
31 31
#include <lemon/core.h>
32 32
#include <lemon/math.h>
33
#include <lemon/maps.h>
34
#include <lemon/circulation.h>
35
#include <lemon/adaptors.h>
36 33

	
37 34
namespace lemon {
38 35

	
39 36
  /// \addtogroup min_cost_flow
40 37
  /// @{
41 38

	
42 39
  /// \brief Implementation of the primal Network Simplex algorithm
43 40
  /// for finding a \ref min_cost_flow "minimum cost flow".
44 41
  ///
45 42
  /// \ref NetworkSimplex implements the primal Network Simplex algorithm
46 43
  /// for finding a \ref min_cost_flow "minimum cost flow".
47 44
  /// This algorithm is a specialized version of the linear programming
48 45
  /// simplex method directly for the minimum cost flow problem.
49 46
  /// It is one of the most efficient solution methods.
50 47
  ///
51 48
  /// In general this class is the fastest implementation available
52 49
  /// in LEMON for the minimum cost flow problem.
53
  /// Moreover it supports both direction of the supply/demand inequality
54
  /// constraints. For more information see \ref ProblemType.
50
  /// Moreover it supports both directions of the supply/demand inequality
51
  /// constraints. For more information see \ref SupplyType.
52
  ///
53
  /// Most of the parameters of the problem (except for the digraph)
54
  /// can be given using separate functions, and the algorithm can be
55
  /// executed using the \ref run() function. If some parameters are not
56
  /// specified, then default values will be used.
55 57
  ///
56 58
  /// \tparam GR The digraph type the algorithm runs on.
57
  /// \tparam F The value type used for flow amounts, capacity bounds
59
  /// \tparam V The value type used for flow amounts, capacity bounds
58 60
  /// and supply values in the algorithm. By default it is \c int.
59 61
  /// \tparam C The value type used for costs and potentials in the
60
  /// algorithm. By default it is the same as \c F.
62
  /// algorithm. By default it is the same as \c V.
61 63
  ///
62 64
  /// \warning Both value types must be signed and all input data must
63 65
  /// be integer.
64 66
  ///
65 67
  /// \note %NetworkSimplex provides five different pivot rule
66 68
  /// implementations, from which the most efficient one is used
67 69
  /// by default. For more information see \ref PivotRule.
68
  template <typename GR, typename F = int, typename C = F>
70
  template <typename GR, typename V = int, typename C = V>
69 71
  class NetworkSimplex
70 72
  {
71 73
  public:
72 74

	
73
    /// The flow type of the algorithm
74
    typedef F Flow;
75
    /// The cost type of the algorithm
75
    /// The type of the flow amounts, capacity bounds and supply values
76
    typedef V Value;
77
    /// The type of the arc costs
76 78
    typedef C Cost;
77
#ifdef DOXYGEN
78
    /// The type of the flow map
79
    typedef GR::ArcMap<Flow> FlowMap;
80
    /// The type of the potential map
81
    typedef GR::NodeMap<Cost> PotentialMap;
82
#else
83
    /// The type of the flow map
84
    typedef typename GR::template ArcMap<Flow> FlowMap;
85
    /// The type of the potential map
86
    typedef typename GR::template NodeMap<Cost> PotentialMap;
87
#endif
88 79

	
89 80
  public:
90 81

	
91
    /// \brief Enum type for selecting the pivot rule.
82
    /// \brief Problem type constants for the \c run() function.
92 83
    ///
93
    /// Enum type for selecting the pivot rule for the \ref run()
84
    /// Enum type containing the problem type constants that can be
85
    /// returned by the \ref run() function of the algorithm.
86
    enum ProblemType {
87
      /// The problem has no feasible solution (flow).
88
      INFEASIBLE,
89
      /// The problem has optimal solution (i.e. it is feasible and
90
      /// bounded), and the algorithm has found optimal flow and node
91
      /// potentials (primal and dual solutions).
92
      OPTIMAL,
93
      /// The objective function of the problem is unbounded, i.e.
94
      /// there is a directed cycle having negative total cost and
95
      /// infinite upper bound.
96
      UNBOUNDED
97
    };
98
    
99
    /// \brief Constants for selecting the type of the supply constraints.
100
    ///
101
    /// Enum type containing constants for selecting the supply type,
102
    /// i.e. the direction of the inequalities in the supply/demand
103
    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
104
    ///
105
    /// The default supply type is \c GEQ, since this form is supported
106
    /// by other minimum cost flow algorithms and the \ref Circulation
107
    /// algorithm, as well.
108
    /// The \c LEQ problem type can be selected using the \ref supplyType()
94 109
    /// function.
95 110
    ///
111
    /// Note that the equality form is a special case of both supply types.
112
    enum SupplyType {
113

	
114
      /// This option means that there are <em>"greater or equal"</em>
115
      /// supply/demand constraints in the definition, i.e. the exact
116
      /// formulation of the problem is the following.
117
      /**
118
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
119
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
120
              sup(u) \quad \forall u\in V \f]
121
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
122
      */
123
      /// It means that the total demand must be greater or equal to the 
124
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
125
      /// negative) and all the supplies have to be carried out from 
126
      /// the supply nodes, but there could be demands that are not 
127
      /// satisfied.
128
      GEQ,
129
      /// It is just an alias for the \c GEQ option.
130
      CARRY_SUPPLIES = GEQ,
131

	
132
      /// This option means that there are <em>"less or equal"</em>
133
      /// supply/demand constraints in the definition, i.e. the exact
134
      /// formulation of the problem is the following.
135
      /**
136
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
137
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
138
              sup(u) \quad \forall u\in V \f]
139
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
140
      */
141
      /// It means that the total demand must be less or equal to the 
142
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
143
      /// positive) and all the demands have to be satisfied, but there
144
      /// could be supplies that are not carried out from the supply
145
      /// nodes.
146
      LEQ,
147
      /// It is just an alias for the \c LEQ option.
148
      SATISFY_DEMANDS = LEQ
149
    };
150
    
151
    /// \brief Constants for selecting the pivot rule.
152
    ///
153
    /// Enum type containing constants for selecting the pivot rule for
154
    /// the \ref run() function.
155
    ///
96 156
    /// \ref NetworkSimplex provides five different pivot rule
97 157
    /// implementations that significantly affect the running time
98 158
    /// of the algorithm.
99 159
    /// By default \ref BLOCK_SEARCH "Block Search" is used, which
100 160
    /// proved to be the most efficient and the most robust on various
101 161
    /// test inputs according to our benchmark tests.
102 162
    /// However another pivot rule can be selected using the \ref run()
103 163
    /// function with the proper parameter.
104 164
    enum PivotRule {
105 165

	
106 166
      /// The First Eligible pivot rule.
107 167
      /// The next eligible arc is selected in a wraparound fashion
108 168
      /// in every iteration.
109 169
      FIRST_ELIGIBLE,
110 170

	
111 171
      /// The Best Eligible pivot rule.
112 172
      /// The best eligible arc is selected in every iteration.
113 173
      BEST_ELIGIBLE,
114 174

	
115 175
      /// The Block Search pivot rule.
116 176
      /// A specified number of arcs are examined in every iteration
117 177
      /// in a wraparound fashion and the best eligible arc is selected
118 178
      /// from this block.
119 179
      BLOCK_SEARCH,
120 180

	
121 181
      /// The Candidate List pivot rule.
122 182
      /// In a major iteration a candidate list is built from eligible arcs
123 183
      /// in a wraparound fashion and in the following minor iterations
124 184
      /// the best eligible arc is selected from this list.
125 185
      CANDIDATE_LIST,
126 186

	
127 187
      /// The Altering Candidate List pivot rule.
128 188
      /// It is a modified version of the Candidate List method.
129 189
      /// It keeps only the several best eligible arcs from the former
130 190
      /// candidate list and extends this list in every iteration.
131 191
      ALTERING_LIST
132 192
    };
133 193
    
134
    /// \brief Enum type for selecting the problem type.
135
    ///
136
    /// Enum type for selecting the problem type, i.e. the direction of
137
    /// the inequalities in the supply/demand constraints of the
138
    /// \ref min_cost_flow "minimum cost flow problem".
139
    ///
140
    /// The default problem type is \c GEQ, since this form is supported
141
    /// by other minimum cost flow algorithms and the \ref Circulation
142
    /// algorithm as well.
143
    /// The \c LEQ problem type can be selected using the \ref problemType()
144
    /// function.
145
    ///
146
    /// Note that the equality form is a special case of both problem type.
147
    enum ProblemType {
148

	
149
      /// This option means that there are "<em>greater or equal</em>"
150
      /// constraints in the defintion, i.e. the exact formulation of the
151
      /// problem is the following.
152
      /**
153
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
154
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
155
              sup(u) \quad \forall u\in V \f]
156
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
157
      */
158
      /// It means that the total demand must be greater or equal to the 
159
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
160
      /// negative) and all the supplies have to be carried out from 
161
      /// the supply nodes, but there could be demands that are not 
162
      /// satisfied.
163
      GEQ,
164
      /// It is just an alias for the \c GEQ option.
165
      CARRY_SUPPLIES = GEQ,
166

	
167
      /// This option means that there are "<em>less or equal</em>"
168
      /// constraints in the defintion, i.e. the exact formulation of the
169
      /// problem is the following.
170
      /**
171
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
172
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
173
              sup(u) \quad \forall u\in V \f]
174
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
175
      */
176
      /// It means that the total demand must be less or equal to the 
177
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
178
      /// positive) and all the demands have to be satisfied, but there
179
      /// could be supplies that are not carried out from the supply
180
      /// nodes.
181
      LEQ,
182
      /// It is just an alias for the \c LEQ option.
183
      SATISFY_DEMANDS = LEQ
184
    };
185

	
186 194
  private:
187 195

	
188 196
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
189 197

	
190
    typedef typename GR::template ArcMap<Flow> FlowArcMap;
191
    typedef typename GR::template ArcMap<Cost> CostArcMap;
192
    typedef typename GR::template NodeMap<Flow> FlowNodeMap;
193

	
194 198
    typedef std::vector<Arc> ArcVector;
195 199
    typedef std::vector<Node> NodeVector;
196 200
    typedef std::vector<int> IntVector;
197 201
    typedef std::vector<bool> BoolVector;
198
    typedef std::vector<Flow> FlowVector;
202
    typedef std::vector<Value> ValueVector;
199 203
    typedef std::vector<Cost> CostVector;
200 204

	
201 205
    // State constants for arcs
202 206
    enum ArcStateEnum {
203 207
      STATE_UPPER = -1,
204 208
      STATE_TREE  =  0,
205 209
      STATE_LOWER =  1
206 210
    };
207 211

	
208 212
  private:
209 213

	
210 214
    // Data related to the underlying digraph
211 215
    const GR &_graph;
212 216
    int _node_num;
213 217
    int _arc_num;
214 218

	
215 219
    // Parameters of the problem
216
    FlowArcMap *_plower;
217
    FlowArcMap *_pupper;
218
    CostArcMap *_pcost;
219
    FlowNodeMap *_psupply;
220
    bool _pstsup;
221
    Node _psource, _ptarget;
222
    Flow _pstflow;
223
    ProblemType _ptype;
224

	
225
    // Result maps
226
    FlowMap *_flow_map;
227
    PotentialMap *_potential_map;
228
    bool _local_flow;
229
    bool _local_potential;
220
    bool _have_lower;
221
    SupplyType _stype;
222
    Value _sum_supply;
230 223

	
231 224
    // Data structures for storing the digraph
232 225
    IntNodeMap _node_id;
233
    ArcVector _arc_ref;
226
    IntArcMap _arc_id;
234 227
    IntVector _source;
235 228
    IntVector _target;
236 229

	
237 230
    // Node and arc data
238
    FlowVector _cap;
231
    ValueVector _lower;
232
    ValueVector _upper;
233
    ValueVector _cap;
239 234
    CostVector _cost;
240
    FlowVector _supply;
241
    FlowVector _flow;
235
    ValueVector _supply;
236
    ValueVector _flow;
242 237
    CostVector _pi;
243 238

	
244 239
    // Data for storing the spanning tree structure
245 240
    IntVector _parent;
246 241
    IntVector _pred;
247 242
    IntVector _thread;
248 243
    IntVector _rev_thread;
249 244
    IntVector _succ_num;
250 245
    IntVector _last_succ;
251 246
    IntVector _dirty_revs;
252 247
    BoolVector _forward;
253 248
    IntVector _state;
254 249
    int _root;
255 250

	
256 251
    // Temporary data used in the current pivot iteration
257 252
    int in_arc, join, u_in, v_in, u_out, v_out;
258 253
    int first, second, right, last;
259 254
    int stem, par_stem, new_stem;
260
    Flow delta;
255
    Value delta;
256

	
257
  public:
258
  
259
    /// \brief Constant for infinite upper bounds (capacities).
260
    ///
261
    /// Constant for infinite upper bounds (capacities).
262
    /// It is \c std::numeric_limits<Value>::infinity() if available,
263
    /// \c std::numeric_limits<Value>::max() otherwise.
264
    const Value INF;
261 265

	
262 266
  private:
263 267

	
264 268
    // Implementation of the First Eligible pivot rule
265 269
    class FirstEligiblePivotRule
266 270
    {
267 271
    private:
268 272

	
269 273
      // References to the NetworkSimplex class
270 274
      const IntVector  &_source;
271 275
      const IntVector  &_target;
272 276
      const CostVector &_cost;
273 277
      const IntVector  &_state;
274 278
      const CostVector &_pi;
275 279
      int &_in_arc;
276 280
      int _arc_num;
277 281

	
278 282
      // Pivot rule data
279 283
      int _next_arc;
280 284

	
281 285
    public:
282 286

	
283 287
      // Constructor
284 288
      FirstEligiblePivotRule(NetworkSimplex &ns) :
285 289
        _source(ns._source), _target(ns._target),
286 290
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
287 291
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
288 292
      {}
289 293

	
290 294
      // Find next entering arc
291 295
      bool findEnteringArc() {
292 296
        Cost c;
293 297
        for (int e = _next_arc; e < _arc_num; ++e) {
294 298
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
295 299
          if (c < 0) {
296 300
            _in_arc = e;
297 301
            _next_arc = e + 1;
298 302
            return true;
299 303
          }
300 304
        }
301 305
        for (int e = 0; e < _next_arc; ++e) {
302 306
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
303 307
          if (c < 0) {
304 308
            _in_arc = e;
305 309
            _next_arc = e + 1;
306 310
            return true;
307 311
          }
308 312
        }
309 313
        return false;
310 314
      }
311 315

	
312 316
    }; //class FirstEligiblePivotRule
313 317

	
314 318

	
315 319
    // Implementation of the Best Eligible pivot rule
316 320
    class BestEligiblePivotRule
317 321
    {
318 322
    private:
319 323

	
320 324
      // References to the NetworkSimplex class
321 325
      const IntVector  &_source;
322 326
      const IntVector  &_target;
323 327
      const CostVector &_cost;
324 328
      const IntVector  &_state;
325 329
      const CostVector &_pi;
326 330
      int &_in_arc;
327 331
      int _arc_num;
328 332

	
329 333
    public:
330 334

	
331 335
      // Constructor
332 336
      BestEligiblePivotRule(NetworkSimplex &ns) :
333 337
        _source(ns._source), _target(ns._target),
334 338
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
335 339
        _in_arc(ns.in_arc), _arc_num(ns._arc_num)
336 340
      {}
337 341

	
338 342
      // Find next entering arc
339 343
      bool findEnteringArc() {
340 344
        Cost c, min = 0;
341 345
        for (int e = 0; e < _arc_num; ++e) {
342 346
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
343 347
          if (c < min) {
344 348
            min = c;
345 349
            _in_arc = e;
346 350
          }
347 351
        }
348 352
        return min < 0;
349 353
      }
350 354

	
351 355
    }; //class BestEligiblePivotRule
352 356

	
353 357

	
354 358
    // Implementation of the Block Search pivot rule
355 359
    class BlockSearchPivotRule
356 360
    {
357 361
    private:
358 362

	
359 363
      // References to the NetworkSimplex class
360 364
      const IntVector  &_source;
361 365
      const IntVector  &_target;
362 366
      const CostVector &_cost;
363 367
      const IntVector  &_state;
364 368
      const CostVector &_pi;
365 369
      int &_in_arc;
366 370
      int _arc_num;
367 371

	
368 372
      // Pivot rule data
369 373
      int _block_size;
370 374
      int _next_arc;
371 375

	
372 376
    public:
373 377

	
374 378
      // Constructor
375 379
      BlockSearchPivotRule(NetworkSimplex &ns) :
376 380
        _source(ns._source), _target(ns._target),
377 381
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
378 382
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
379 383
      {
380 384
        // The main parameters of the pivot rule
381 385
        const double BLOCK_SIZE_FACTOR = 2.0;
382 386
        const int MIN_BLOCK_SIZE = 10;
383 387

	
384 388
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
385 389
                                    std::sqrt(double(_arc_num))),
386 390
                                MIN_BLOCK_SIZE );
387 391
      }
388 392

	
389 393
      // Find next entering arc
390 394
      bool findEnteringArc() {
391 395
        Cost c, min = 0;
392 396
        int cnt = _block_size;
393 397
        int e, min_arc = _next_arc;
394 398
        for (e = _next_arc; e < _arc_num; ++e) {
395 399
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
396 400
          if (c < min) {
397 401
            min = c;
398 402
            min_arc = e;
399 403
          }
400 404
          if (--cnt == 0) {
401 405
            if (min < 0) break;
402 406
            cnt = _block_size;
403 407
          }
404 408
        }
405 409
        if (min == 0 || cnt > 0) {
406 410
          for (e = 0; e < _next_arc; ++e) {
407 411
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
408 412
            if (c < min) {
409 413
              min = c;
410 414
              min_arc = e;
411 415
            }
412 416
            if (--cnt == 0) {
413 417
              if (min < 0) break;
414 418
              cnt = _block_size;
415 419
            }
416 420
          }
417 421
        }
418 422
        if (min >= 0) return false;
419 423
        _in_arc = min_arc;
420 424
        _next_arc = e;
421 425
        return true;
422 426
      }
423 427

	
424 428
    }; //class BlockSearchPivotRule
425 429

	
426 430

	
427 431
    // Implementation of the Candidate List pivot rule
428 432
    class CandidateListPivotRule
429 433
    {
430 434
    private:
431 435

	
432 436
      // References to the NetworkSimplex class
433 437
      const IntVector  &_source;
434 438
      const IntVector  &_target;
435 439
      const CostVector &_cost;
436 440
      const IntVector  &_state;
437 441
      const CostVector &_pi;
438 442
      int &_in_arc;
439 443
      int _arc_num;
440 444

	
441 445
      // Pivot rule data
442 446
      IntVector _candidates;
443 447
      int _list_length, _minor_limit;
444 448
      int _curr_length, _minor_count;
445 449
      int _next_arc;
446 450

	
447 451
    public:
448 452

	
449 453
      /// Constructor
450 454
      CandidateListPivotRule(NetworkSimplex &ns) :
451 455
        _source(ns._source), _target(ns._target),
452 456
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
453 457
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
454 458
      {
455 459
        // The main parameters of the pivot rule
456 460
        const double LIST_LENGTH_FACTOR = 1.0;
457 461
        const int MIN_LIST_LENGTH = 10;
458 462
        const double MINOR_LIMIT_FACTOR = 0.1;
459 463
        const int MIN_MINOR_LIMIT = 3;
460 464

	
461 465
        _list_length = std::max( int(LIST_LENGTH_FACTOR *
462 466
                                     std::sqrt(double(_arc_num))),
463 467
                                 MIN_LIST_LENGTH );
464 468
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
465 469
                                 MIN_MINOR_LIMIT );
466 470
        _curr_length = _minor_count = 0;
467 471
        _candidates.resize(_list_length);
468 472
      }
469 473

	
470 474
      /// Find next entering arc
471 475
      bool findEnteringArc() {
472 476
        Cost min, c;
473 477
        int e, min_arc = _next_arc;
474 478
        if (_curr_length > 0 && _minor_count < _minor_limit) {
475 479
          // Minor iteration: select the best eligible arc from the
476 480
          // current candidate list
477 481
          ++_minor_count;
478 482
          min = 0;
479 483
          for (int i = 0; i < _curr_length; ++i) {
480 484
            e = _candidates[i];
481 485
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
482 486
            if (c < min) {
483 487
              min = c;
484 488
              min_arc = e;
485 489
            }
486 490
            if (c >= 0) {
487 491
              _candidates[i--] = _candidates[--_curr_length];
488 492
            }
489 493
          }
490 494
          if (min < 0) {
491 495
            _in_arc = min_arc;
492 496
            return true;
493 497
          }
494 498
        }
495 499

	
496 500
        // Major iteration: build a new candidate list
497 501
        min = 0;
498 502
        _curr_length = 0;
499 503
        for (e = _next_arc; e < _arc_num; ++e) {
500 504
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
501 505
          if (c < 0) {
502 506
            _candidates[_curr_length++] = e;
503 507
            if (c < min) {
504 508
              min = c;
505 509
              min_arc = e;
506 510
            }
507 511
            if (_curr_length == _list_length) break;
508 512
          }
509 513
        }
510 514
        if (_curr_length < _list_length) {
511 515
          for (e = 0; e < _next_arc; ++e) {
512 516
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
513 517
            if (c < 0) {
514 518
              _candidates[_curr_length++] = e;
515 519
              if (c < min) {
516 520
                min = c;
517 521
                min_arc = e;
518 522
              }
519 523
              if (_curr_length == _list_length) break;
520 524
            }
521 525
          }
522 526
        }
523 527
        if (_curr_length == 0) return false;
524 528
        _minor_count = 1;
525 529
        _in_arc = min_arc;
526 530
        _next_arc = e;
527 531
        return true;
528 532
      }
529 533

	
530 534
    }; //class CandidateListPivotRule
531 535

	
532 536

	
533 537
    // Implementation of the Altering Candidate List pivot rule
534 538
    class AlteringListPivotRule
535 539
    {
536 540
    private:
537 541

	
538 542
      // References to the NetworkSimplex class
539 543
      const IntVector  &_source;
540 544
      const IntVector  &_target;
541 545
      const CostVector &_cost;
542 546
      const IntVector  &_state;
543 547
      const CostVector &_pi;
544 548
      int &_in_arc;
545 549
      int _arc_num;
546 550

	
547 551
      // Pivot rule data
548 552
      int _block_size, _head_length, _curr_length;
549 553
      int _next_arc;
550 554
      IntVector _candidates;
551 555
      CostVector _cand_cost;
552 556

	
553 557
      // Functor class to compare arcs during sort of the candidate list
554 558
      class SortFunc
555 559
      {
556 560
      private:
557 561
        const CostVector &_map;
558 562
      public:
559 563
        SortFunc(const CostVector &map) : _map(map) {}
560 564
        bool operator()(int left, int right) {
561 565
          return _map[left] > _map[right];
562 566
        }
563 567
      };
564 568

	
565 569
      SortFunc _sort_func;
566 570

	
567 571
    public:
568 572

	
569 573
      // Constructor
570 574
      AlteringListPivotRule(NetworkSimplex &ns) :
571 575
        _source(ns._source), _target(ns._target),
572 576
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
573 577
        _in_arc(ns.in_arc), _arc_num(ns._arc_num),
574 578
        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
575 579
      {
576 580
        // The main parameters of the pivot rule
577 581
        const double BLOCK_SIZE_FACTOR = 1.5;
578 582
        const int MIN_BLOCK_SIZE = 10;
579 583
        const double HEAD_LENGTH_FACTOR = 0.1;
580 584
        const int MIN_HEAD_LENGTH = 3;
581 585

	
582 586
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
583 587
                                    std::sqrt(double(_arc_num))),
584 588
                                MIN_BLOCK_SIZE );
585 589
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
586 590
                                 MIN_HEAD_LENGTH );
587 591
        _candidates.resize(_head_length + _block_size);
588 592
        _curr_length = 0;
589 593
      }
590 594

	
591 595
      // Find next entering arc
592 596
      bool findEnteringArc() {
593 597
        // Check the current candidate list
594 598
        int e;
595 599
        for (int i = 0; i < _curr_length; ++i) {
596 600
          e = _candidates[i];
597 601
          _cand_cost[e] = _state[e] *
598 602
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
599 603
          if (_cand_cost[e] >= 0) {
600 604
            _candidates[i--] = _candidates[--_curr_length];
601 605
          }
602 606
        }
603 607

	
604 608
        // Extend the list
605 609
        int cnt = _block_size;
606 610
        int last_arc = 0;
607 611
        int limit = _head_length;
608 612

	
609 613
        for (int e = _next_arc; e < _arc_num; ++e) {
610 614
          _cand_cost[e] = _state[e] *
611 615
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
612 616
          if (_cand_cost[e] < 0) {
613 617
            _candidates[_curr_length++] = e;
614 618
            last_arc = e;
615 619
          }
616 620
          if (--cnt == 0) {
617 621
            if (_curr_length > limit) break;
618 622
            limit = 0;
619 623
            cnt = _block_size;
620 624
          }
621 625
        }
622 626
        if (_curr_length <= limit) {
623 627
          for (int e = 0; e < _next_arc; ++e) {
624 628
            _cand_cost[e] = _state[e] *
625 629
              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
626 630
            if (_cand_cost[e] < 0) {
627 631
              _candidates[_curr_length++] = e;
628 632
              last_arc = e;
629 633
            }
630 634
            if (--cnt == 0) {
631 635
              if (_curr_length > limit) break;
632 636
              limit = 0;
633 637
              cnt = _block_size;
634 638
            }
635 639
          }
636 640
        }
637 641
        if (_curr_length == 0) return false;
638 642
        _next_arc = last_arc + 1;
639 643

	
640 644
        // Make heap of the candidate list (approximating a partial sort)
641 645
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
642 646
                   _sort_func );
643 647

	
644 648
        // Pop the first element of the heap
645 649
        _in_arc = _candidates[0];
646 650
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
647 651
                  _sort_func );
648 652
        _curr_length = std::min(_head_length, _curr_length - 1);
649 653
        return true;
650 654
      }
651 655

	
652 656
    }; //class AlteringListPivotRule
653 657

	
654 658
  public:
655 659

	
656 660
    /// \brief Constructor.
657 661
    ///
658 662
    /// The constructor of the class.
659 663
    ///
660 664
    /// \param graph The digraph the algorithm runs on.
661 665
    NetworkSimplex(const GR& graph) :
662
      _graph(graph),
663
      _plower(NULL), _pupper(NULL), _pcost(NULL),
664
      _psupply(NULL), _pstsup(false), _ptype(GEQ),
665
      _flow_map(NULL), _potential_map(NULL),
666
      _local_flow(false), _local_potential(false),
667
      _node_id(graph)
666
      _graph(graph), _node_id(graph), _arc_id(graph),
667
      INF(std::numeric_limits<Value>::has_infinity ?
668
          std::numeric_limits<Value>::infinity() :
669
          std::numeric_limits<Value>::max())
668 670
    {
669
      LEMON_ASSERT(std::numeric_limits<Flow>::is_integer &&
670
                   std::numeric_limits<Flow>::is_signed,
671
        "The flow type of NetworkSimplex must be signed integer");
672
      LEMON_ASSERT(std::numeric_limits<Cost>::is_integer &&
673
                   std::numeric_limits<Cost>::is_signed,
674
        "The cost type of NetworkSimplex must be signed integer");
675
    }
671
      // Check the value types
672
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
673
        "The flow type of NetworkSimplex must be signed");
674
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
675
        "The cost type of NetworkSimplex must be signed");
676
        
677
      // Resize vectors
678
      _node_num = countNodes(_graph);
679
      _arc_num = countArcs(_graph);
680
      int all_node_num = _node_num + 1;
681
      int all_arc_num = _arc_num + _node_num;
676 682

	
677
    /// Destructor.
678
    ~NetworkSimplex() {
679
      if (_local_flow) delete _flow_map;
680
      if (_local_potential) delete _potential_map;
683
      _source.resize(all_arc_num);
684
      _target.resize(all_arc_num);
685

	
686
      _lower.resize(all_arc_num);
687
      _upper.resize(all_arc_num);
688
      _cap.resize(all_arc_num);
689
      _cost.resize(all_arc_num);
690
      _supply.resize(all_node_num);
691
      _flow.resize(all_arc_num);
692
      _pi.resize(all_node_num);
693

	
694
      _parent.resize(all_node_num);
695
      _pred.resize(all_node_num);
696
      _forward.resize(all_node_num);
697
      _thread.resize(all_node_num);
698
      _rev_thread.resize(all_node_num);
699
      _succ_num.resize(all_node_num);
700
      _last_succ.resize(all_node_num);
701
      _state.resize(all_arc_num);
702

	
703
      // Copy the graph (store the arcs in a mixed order)
704
      int i = 0;
705
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
706
        _node_id[n] = i;
707
      }
708
      int k = std::max(int(std::sqrt(double(_arc_num))), 10);
709
      i = 0;
710
      for (ArcIt a(_graph); a != INVALID; ++a) {
711
        _arc_id[a] = i;
712
        _source[i] = _node_id[_graph.source(a)];
713
        _target[i] = _node_id[_graph.target(a)];
714
        if ((i += k) >= _arc_num) i = (i % k) + 1;
715
      }
716
      
717
      // Initialize maps
718
      for (int i = 0; i != _node_num; ++i) {
719
        _supply[i] = 0;
720
      }
721
      for (int i = 0; i != _arc_num; ++i) {
722
        _lower[i] = 0;
723
        _upper[i] = INF;
724
        _cost[i] = 1;
725
      }
726
      _have_lower = false;
727
      _stype = GEQ;
681 728
    }
682 729

	
683 730
    /// \name Parameters
684 731
    /// The parameters of the algorithm can be specified using these
685 732
    /// functions.
686 733

	
687 734
    /// @{
688 735

	
689 736
    /// \brief Set the lower bounds on the arcs.
690 737
    ///
691 738
    /// This function sets the lower bounds on the arcs.
692
    /// If neither this function nor \ref boundMaps() is used before
693
    /// calling \ref run(), the lower bounds will be set to zero
694
    /// on all arcs.
739
    /// If it is not used before calling \ref run(), the lower bounds
740
    /// will be set to zero on all arcs.
695 741
    ///
696 742
    /// \param map An arc map storing the lower bounds.
697
    /// Its \c Value type must be convertible to the \c Flow type
743
    /// Its \c Value type must be convertible to the \c Value type
698 744
    /// of the algorithm.
699 745
    ///
700 746
    /// \return <tt>(*this)</tt>
701
    template <typename LOWER>
702
    NetworkSimplex& lowerMap(const LOWER& map) {
703
      delete _plower;
704
      _plower = new FlowArcMap(_graph);
747
    template <typename LowerMap>
748
    NetworkSimplex& lowerMap(const LowerMap& map) {
749
      _have_lower = true;
705 750
      for (ArcIt a(_graph); a != INVALID; ++a) {
706
        (*_plower)[a] = map[a];
751
        _lower[_arc_id[a]] = map[a];
707 752
      }
708 753
      return *this;
709 754
    }
710 755

	
711 756
    /// \brief Set the upper bounds (capacities) on the arcs.
712 757
    ///
713 758
    /// This function sets the upper bounds (capacities) on the arcs.
714
    /// If none of the functions \ref upperMap(), \ref capacityMap()
715
    /// and \ref boundMaps() is used before calling \ref run(),
716
    /// the upper bounds (capacities) will be set to
717
    /// \c std::numeric_limits<Flow>::max() on all arcs.
759
    /// If it is not used before calling \ref run(), the upper bounds
760
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
761
    /// unbounded from above on each arc).
718 762
    ///
719 763
    /// \param map An arc map storing the upper bounds.
720
    /// Its \c Value type must be convertible to the \c Flow type
764
    /// Its \c Value type must be convertible to the \c Value type
721 765
    /// of the algorithm.
722 766
    ///
723 767
    /// \return <tt>(*this)</tt>
724
    template<typename UPPER>
725
    NetworkSimplex& upperMap(const UPPER& map) {
726
      delete _pupper;
727
      _pupper = new FlowArcMap(_graph);
768
    template<typename UpperMap>
769
    NetworkSimplex& upperMap(const UpperMap& map) {
728 770
      for (ArcIt a(_graph); a != INVALID; ++a) {
729
        (*_pupper)[a] = map[a];
771
        _upper[_arc_id[a]] = map[a];
730 772
      }
731 773
      return *this;
732 774
    }
733 775

	
734
    /// \brief Set the upper bounds (capacities) on the arcs.
735
    ///
736
    /// This function sets the upper bounds (capacities) on the arcs.
737
    /// It is just an alias for \ref upperMap().
738
    ///
739
    /// \return <tt>(*this)</tt>
740
    template<typename CAP>
741
    NetworkSimplex& capacityMap(const CAP& map) {
742
      return upperMap(map);
743
    }
744

	
745
    /// \brief Set the lower and upper bounds on the arcs.
746
    ///
747
    /// This function sets the lower and upper bounds on the arcs.
748
    /// If neither this function nor \ref lowerMap() is used before
749
    /// calling \ref run(), the lower bounds will be set to zero
750
    /// on all arcs.
751
    /// If none of the functions \ref upperMap(), \ref capacityMap()
752
    /// and \ref boundMaps() is used before calling \ref run(),
753
    /// the upper bounds (capacities) will be set to
754
    /// \c std::numeric_limits<Flow>::max() on all arcs.
755
    ///
756
    /// \param lower An arc map storing the lower bounds.
757
    /// \param upper An arc map storing the upper bounds.
758
    ///
759
    /// The \c Value type of the maps must be convertible to the
760
    /// \c Flow type of the algorithm.
761
    ///
762
    /// \note This function is just a shortcut of calling \ref lowerMap()
763
    /// and \ref upperMap() separately.
764
    ///
765
    /// \return <tt>(*this)</tt>
766
    template <typename LOWER, typename UPPER>
767
    NetworkSimplex& boundMaps(const LOWER& lower, const UPPER& upper) {
768
      return lowerMap(lower).upperMap(upper);
769
    }
770

	
771 776
    /// \brief Set the costs of the arcs.
772 777
    ///
773 778
    /// This function sets the costs of the arcs.
774 779
    /// If it is not used before calling \ref run(), the costs
775 780
    /// will be set to \c 1 on all arcs.
776 781
    ///
777 782
    /// \param map An arc map storing the costs.
778 783
    /// Its \c Value type must be convertible to the \c Cost type
779 784
    /// of the algorithm.
780 785
    ///
781 786
    /// \return <tt>(*this)</tt>
782
    template<typename COST>
783
    NetworkSimplex& costMap(const COST& map) {
784
      delete _pcost;
785
      _pcost = new CostArcMap(_graph);
787
    template<typename CostMap>
788
    NetworkSimplex& costMap(const CostMap& map) {
786 789
      for (ArcIt a(_graph); a != INVALID; ++a) {
787
        (*_pcost)[a] = map[a];
790
        _cost[_arc_id[a]] = map[a];
788 791
      }
789 792
      return *this;
790 793
    }
791 794

	
792 795
    /// \brief Set the supply values of the nodes.
793 796
    ///
794 797
    /// This function sets the supply values of the nodes.
795 798
    /// If neither this function nor \ref stSupply() is used before
796 799
    /// calling \ref run(), the supply of each node will be set to zero.
797 800
    /// (It makes sense only if non-zero lower bounds are given.)
798 801
    ///
799 802
    /// \param map A node map storing the supply values.
800
    /// Its \c Value type must be convertible to the \c Flow type
803
    /// Its \c Value type must be convertible to the \c Value type
801 804
    /// of the algorithm.
802 805
    ///
803 806
    /// \return <tt>(*this)</tt>
804
    template<typename SUP>
805
    NetworkSimplex& supplyMap(const SUP& map) {
806
      delete _psupply;
807
      _pstsup = false;
808
      _psupply = new FlowNodeMap(_graph);
807
    template<typename SupplyMap>
808
    NetworkSimplex& supplyMap(const SupplyMap& map) {
809 809
      for (NodeIt n(_graph); n != INVALID; ++n) {
810
        (*_psupply)[n] = map[n];
810
        _supply[_node_id[n]] = map[n];
811 811
      }
812 812
      return *this;
813 813
    }
814 814

	
815 815
    /// \brief Set single source and target nodes and a supply value.
816 816
    ///
817 817
    /// This function sets a single source node and a single target node
818 818
    /// and the required flow value.
819 819
    /// If neither this function nor \ref supplyMap() is used before
820 820
    /// calling \ref run(), the supply of each node will be set to zero.
821 821
    /// (It makes sense only if non-zero lower bounds are given.)
822 822
    ///
823
    /// Using this function has the same effect as using \ref supplyMap()
824
    /// with such a map in which \c k is assigned to \c s, \c -k is
825
    /// assigned to \c t and all other nodes have zero supply value.
826
    ///
823 827
    /// \param s The source node.
824 828
    /// \param t The target node.
825 829
    /// \param k The required amount of flow from node \c s to node \c t
826 830
    /// (i.e. the supply of \c s and the demand of \c t).
827 831
    ///
828 832
    /// \return <tt>(*this)</tt>
829
    NetworkSimplex& stSupply(const Node& s, const Node& t, Flow k) {
830
      delete _psupply;
831
      _psupply = NULL;
832
      _pstsup = true;
833
      _psource = s;
834
      _ptarget = t;
835
      _pstflow = k;
833
    NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
834
      for (int i = 0; i != _node_num; ++i) {
835
        _supply[i] = 0;
836
      }
837
      _supply[_node_id[s]] =  k;
838
      _supply[_node_id[t]] = -k;
836 839
      return *this;
837 840
    }
838 841
    
839
    /// \brief Set the problem type.
842
    /// \brief Set the type of the supply constraints.
840 843
    ///
841
    /// This function sets the problem type for the algorithm.
842
    /// If it is not used before calling \ref run(), the \ref GEQ problem
844
    /// This function sets the type of the supply/demand constraints.
845
    /// If it is not used before calling \ref run(), the \ref GEQ supply
843 846
    /// type will be used.
844 847
    ///
845
    /// For more information see \ref ProblemType.
848
    /// For more information see \ref SupplyType.
846 849
    ///
847 850
    /// \return <tt>(*this)</tt>
848
    NetworkSimplex& problemType(ProblemType problem_type) {
849
      _ptype = problem_type;
851
    NetworkSimplex& supplyType(SupplyType supply_type) {
852
      _stype = supply_type;
850 853
      return *this;
851 854
    }
852 855

	
853
    /// \brief Set the flow map.
854
    ///
855
    /// This function sets the flow map.
856
    /// If it is not used before calling \ref run(), an instance will
857
    /// be allocated automatically. The destructor deallocates this
858
    /// automatically allocated map, of course.
859
    ///
860
    /// \return <tt>(*this)</tt>
861
    NetworkSimplex& flowMap(FlowMap& map) {
862
      if (_local_flow) {
863
        delete _flow_map;
864
        _local_flow = false;
865
      }
866
      _flow_map = &map;
867
      return *this;
868
    }
869

	
870
    /// \brief Set the potential map.
871
    ///
872
    /// This function sets the potential map, which is used for storing
873
    /// the dual solution.
874
    /// If it is not used before calling \ref run(), an instance will
875
    /// be allocated automatically. The destructor deallocates this
876
    /// automatically allocated map, of course.
877
    ///
878
    /// \return <tt>(*this)</tt>
879
    NetworkSimplex& potentialMap(PotentialMap& map) {
880
      if (_local_potential) {
881
        delete _potential_map;
882
        _local_potential = false;
883
      }
884
      _potential_map = &map;
885
      return *this;
886
    }
887
    
888 856
    /// @}
889 857

	
890 858
    /// \name Execution Control
891 859
    /// The algorithm can be executed using \ref run().
892 860

	
893 861
    /// @{
894 862

	
895 863
    /// \brief Run the algorithm.
896 864
    ///
897 865
    /// This function runs the algorithm.
898 866
    /// The paramters can be specified using functions \ref lowerMap(),
899
    /// \ref upperMap(), \ref capacityMap(), \ref boundMaps(),
900
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), 
901
    /// \ref problemType(), \ref flowMap() and \ref potentialMap().
867
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), 
868
    /// \ref supplyType().
902 869
    /// For example,
903 870
    /// \code
904 871
    ///   NetworkSimplex<ListDigraph> ns(graph);
905
    ///   ns.boundMaps(lower, upper).costMap(cost)
872
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
906 873
    ///     .supplyMap(sup).run();
907 874
    /// \endcode
908 875
    ///
909 876
    /// This function can be called more than once. All the parameters
910 877
    /// that have been given are kept for the next call, unless
911 878
    /// \ref reset() is called, thus only the modified parameters
912 879
    /// have to be set again. See \ref reset() for examples.
880
    /// However the underlying digraph must not be modified after this
881
    /// class have been constructed, since it copies and extends the graph.
913 882
    ///
914 883
    /// \param pivot_rule The pivot rule that will be used during the
915 884
    /// algorithm. For more information see \ref PivotRule.
916 885
    ///
917
    /// \return \c true if a feasible flow can be found.
918
    bool run(PivotRule pivot_rule = BLOCK_SEARCH) {
919
      return init() && start(pivot_rule);
886
    /// \return \c INFEASIBLE if no feasible flow exists,
887
    /// \n \c OPTIMAL if the problem has optimal solution
888
    /// (i.e. it is feasible and bounded), and the algorithm has found
889
    /// optimal flow and node potentials (primal and dual solutions),
890
    /// \n \c UNBOUNDED if the objective function of the problem is
891
    /// unbounded, i.e. there is a directed cycle having negative total
892
    /// cost and infinite upper bound.
893
    ///
894
    /// \see ProblemType, PivotRule
895
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
896
      if (!init()) return INFEASIBLE;
897
      return start(pivot_rule);
920 898
    }
921 899

	
922 900
    /// \brief Reset all the parameters that have been given before.
923 901
    ///
924 902
    /// This function resets all the paramaters that have been given
925 903
    /// before using functions \ref lowerMap(), \ref upperMap(),
926
    /// \ref capacityMap(), \ref boundMaps(), \ref costMap(),
927
    /// \ref supplyMap(), \ref stSupply(), \ref problemType(), 
928
    /// \ref flowMap() and \ref potentialMap().
904
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
929 905
    ///
930 906
    /// It is useful for multiple run() calls. If this function is not
931 907
    /// used, all the parameters given before are kept for the next
932 908
    /// \ref run() call.
909
    /// However the underlying digraph must not be modified after this
910
    /// class have been constructed, since it copies and extends the graph.
933 911
    ///
934 912
    /// For example,
935 913
    /// \code
936 914
    ///   NetworkSimplex<ListDigraph> ns(graph);
937 915
    ///
938 916
    ///   // First run
939
    ///   ns.lowerMap(lower).capacityMap(cap).costMap(cost)
917
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
940 918
    ///     .supplyMap(sup).run();
941 919
    ///
942 920
    ///   // Run again with modified cost map (reset() is not called,
943 921
    ///   // so only the cost map have to be set again)
944 922
    ///   cost[e] += 100;
945 923
    ///   ns.costMap(cost).run();
946 924
    ///
947 925
    ///   // Run again from scratch using reset()
948 926
    ///   // (the lower bounds will be set to zero on all arcs)
949 927
    ///   ns.reset();
950
    ///   ns.capacityMap(cap).costMap(cost)
928
    ///   ns.upperMap(capacity).costMap(cost)
951 929
    ///     .supplyMap(sup).run();
952 930
    /// \endcode
953 931
    ///
954 932
    /// \return <tt>(*this)</tt>
955 933
    NetworkSimplex& reset() {
956
      delete _plower;
957
      delete _pupper;
958
      delete _pcost;
959
      delete _psupply;
960
      _plower = NULL;
961
      _pupper = NULL;
962
      _pcost = NULL;
963
      _psupply = NULL;
964
      _pstsup = false;
965
      _ptype = GEQ;
966
      if (_local_flow) delete _flow_map;
967
      if (_local_potential) delete _potential_map;
968
      _flow_map = NULL;
969
      _potential_map = NULL;
970
      _local_flow = false;
971
      _local_potential = false;
972

	
934
      for (int i = 0; i != _node_num; ++i) {
935
        _supply[i] = 0;
936
      }
937
      for (int i = 0; i != _arc_num; ++i) {
938
        _lower[i] = 0;
939
        _upper[i] = INF;
940
        _cost[i] = 1;
941
      }
942
      _have_lower = false;
943
      _stype = GEQ;
973 944
      return *this;
974 945
    }
975 946

	
976 947
    /// @}
977 948

	
978 949
    /// \name Query Functions
979 950
    /// The results of the algorithm can be obtained using these
980 951
    /// functions.\n
981 952
    /// The \ref run() function must be called before using them.
982 953

	
983 954
    /// @{
984 955

	
985 956
    /// \brief Return the total cost of the found flow.
986 957
    ///
987 958
    /// This function returns the total cost of the found flow.
988
    /// The complexity of the function is O(e).
959
    /// Its complexity is O(e).
989 960
    ///
990 961
    /// \note The return type of the function can be specified as a
991 962
    /// template parameter. For example,
992 963
    /// \code
993 964
    ///   ns.totalCost<double>();
994 965
    /// \endcode
995 966
    /// It is useful if the total cost cannot be stored in the \c Cost
996 967
    /// type of the algorithm, which is the default return type of the
997 968
    /// function.
998 969
    ///
999 970
    /// \pre \ref run() must be called before using this function.
1000
    template <typename Num>
1001
    Num totalCost() const {
1002
      Num c = 0;
1003
      if (_pcost) {
1004
        for (ArcIt e(_graph); e != INVALID; ++e)
1005
          c += (*_flow_map)[e] * (*_pcost)[e];
1006
      } else {
1007
        for (ArcIt e(_graph); e != INVALID; ++e)
1008
          c += (*_flow_map)[e];
971
    template <typename Number>
972
    Number totalCost() const {
973
      Number c = 0;
974
      for (ArcIt a(_graph); a != INVALID; ++a) {
975
        int i = _arc_id[a];
976
        c += Number(_flow[i]) * Number(_cost[i]);
1009 977
      }
1010 978
      return c;
1011 979
    }
1012 980

	
1013 981
#ifndef DOXYGEN
1014 982
    Cost totalCost() const {
1015 983
      return totalCost<Cost>();
1016 984
    }
1017 985
#endif
1018 986

	
1019 987
    /// \brief Return the flow on the given arc.
1020 988
    ///
1021 989
    /// This function returns the flow on the given arc.
1022 990
    ///
1023 991
    /// \pre \ref run() must be called before using this function.
1024
    Flow flow(const Arc& a) const {
1025
      return (*_flow_map)[a];
992
    Value flow(const Arc& a) const {
993
      return _flow[_arc_id[a]];
1026 994
    }
1027 995

	
1028
    /// \brief Return a const reference to the flow map.
996
    /// \brief Return the flow map (the primal solution).
1029 997
    ///
1030
    /// This function returns a const reference to an arc map storing
1031
    /// the found flow.
998
    /// This function copies the flow value on each arc into the given
999
    /// map. The \c Value type of the algorithm must be convertible to
1000
    /// the \c Value type of the map.
1032 1001
    ///
1033 1002
    /// \pre \ref run() must be called before using this function.
1034
    const FlowMap& flowMap() const {
1035
      return *_flow_map;
1003
    template <typename FlowMap>
1004
    void flowMap(FlowMap &map) const {
1005
      for (ArcIt a(_graph); a != INVALID; ++a) {
1006
        map.set(a, _flow[_arc_id[a]]);
1007
      }
1036 1008
    }
1037 1009

	
1038 1010
    /// \brief Return the potential (dual value) of the given node.
1039 1011
    ///
1040 1012
    /// This function returns the potential (dual value) of the
1041 1013
    /// given node.
1042 1014
    ///
1043 1015
    /// \pre \ref run() must be called before using this function.
1044 1016
    Cost potential(const Node& n) const {
1045
      return (*_potential_map)[n];
1017
      return _pi[_node_id[n]];
1046 1018
    }
1047 1019

	
1048
    /// \brief Return a const reference to the potential map
1049
    /// (the dual solution).
1020
    /// \brief Return the potential map (the dual solution).
1050 1021
    ///
1051
    /// This function returns a const reference to a node map storing
1052
    /// the found potentials, which form the dual solution of the
1053
    /// \ref min_cost_flow "minimum cost flow" problem.
1022
    /// This function copies the potential (dual value) of each node
1023
    /// into the given map.
1024
    /// The \c Cost type of the algorithm must be convertible to the
1025
    /// \c Value type of the map.
1054 1026
    ///
1055 1027
    /// \pre \ref run() must be called before using this function.
1056
    const PotentialMap& potentialMap() const {
1057
      return *_potential_map;
1028
    template <typename PotentialMap>
1029
    void potentialMap(PotentialMap &map) const {
1030
      for (NodeIt n(_graph); n != INVALID; ++n) {
1031
        map.set(n, _pi[_node_id[n]]);
1032
      }
1058 1033
    }
1059 1034

	
1060 1035
    /// @}
1061 1036

	
1062 1037
  private:
1063 1038

	
1064 1039
    // Initialize internal data structures
1065 1040
    bool init() {
1066
      // Initialize result maps
1067
      if (!_flow_map) {
1068
        _flow_map = new FlowMap(_graph);
1069
        _local_flow = true;
1041
      if (_node_num == 0) return false;
1042

	
1043
      // Check the sum of supply values
1044
      _sum_supply = 0;
1045
      for (int i = 0; i != _node_num; ++i) {
1046
        _sum_supply += _supply[i];
1070 1047
      }
1071
      if (!_potential_map) {
1072
        _potential_map = new PotentialMap(_graph);
1073
        _local_potential = true;
1048
      if ( !((_stype == GEQ && _sum_supply <= 0) ||
1049
             (_stype == LEQ && _sum_supply >= 0)) ) return false;
1050

	
1051
      // Remove non-zero lower bounds
1052
      if (_have_lower) {
1053
        for (int i = 0; i != _arc_num; ++i) {
1054
          Value c = _lower[i];
1055
          if (c >= 0) {
1056
            _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
1057
          } else {
1058
            _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
1059
          }
1060
          _supply[_source[i]] -= c;
1061
          _supply[_target[i]] += c;
1062
        }
1063
      } else {
1064
        for (int i = 0; i != _arc_num; ++i) {
1065
          _cap[i] = _upper[i];
1066
        }
1074 1067
      }
1075 1068

	
1076
      // Initialize vectors
1077
      _node_num = countNodes(_graph);
1078
      _arc_num = countArcs(_graph);
1079
      int all_node_num = _node_num + 1;
1080
      int all_arc_num = _arc_num + _node_num;
1081
      if (_node_num == 0) return false;
1082

	
1083
      _arc_ref.resize(_arc_num);
1084
      _source.resize(all_arc_num);
1085
      _target.resize(all_arc_num);
1086

	
1087
      _cap.resize(all_arc_num);
1088
      _cost.resize(all_arc_num);
1089
      _supply.resize(all_node_num);
1090
      _flow.resize(all_arc_num);
1091
      _pi.resize(all_node_num);
1092

	
1093
      _parent.resize(all_node_num);
1094
      _pred.resize(all_node_num);
1095
      _forward.resize(all_node_num);
1096
      _thread.resize(all_node_num);
1097
      _rev_thread.resize(all_node_num);
1098
      _succ_num.resize(all_node_num);
1099
      _last_succ.resize(all_node_num);
1100
      _state.resize(all_arc_num);
1101

	
1102
      // Initialize node related data
1103
      bool valid_supply = true;
1104
      Flow sum_supply = 0;
1105
      if (!_pstsup && !_psupply) {
1106
        _pstsup = true;
1107
        _psource = _ptarget = NodeIt(_graph);
1108
        _pstflow = 0;
1109
      }
1110
      if (_psupply) {
1111
        int i = 0;
1112
        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1113
          _node_id[n] = i;
1114
          _supply[i] = (*_psupply)[n];
1115
          sum_supply += _supply[i];
1069
      // Initialize artifical cost
1070
      Cost ART_COST;
1071
      if (std::numeric_limits<Cost>::is_exact) {
1072
        ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
1073
      } else {
1074
        ART_COST = std::numeric_limits<Cost>::min();
1075
        for (int i = 0; i != _arc_num; ++i) {
1076
          if (_cost[i] > ART_COST) ART_COST = _cost[i];
1116 1077
        }
1117
        valid_supply = (_ptype == GEQ && sum_supply <= 0) ||
1118
                       (_ptype == LEQ && sum_supply >= 0);
1119
      } else {
1120
        int i = 0;
1121
        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1122
          _node_id[n] = i;
1123
          _supply[i] = 0;
1124
        }
1125
        _supply[_node_id[_psource]] =  _pstflow;
1126
        _supply[_node_id[_ptarget]] = -_pstflow;
1127
      }
1128
      if (!valid_supply) return false;
1129

	
1130
      // Infinite capacity value
1131
      Flow inf_cap =
1132
        std::numeric_limits<Flow>::has_infinity ?
1133
        std::numeric_limits<Flow>::infinity() :
1134
        std::numeric_limits<Flow>::max();
1135

	
1136
      // Initialize artifical cost
1137
      Cost art_cost;
1138
      if (std::numeric_limits<Cost>::is_exact) {
1139
        art_cost = std::numeric_limits<Cost>::max() / 4 + 1;
1140
      } else {
1141
        art_cost = std::numeric_limits<Cost>::min();
1142
        for (int i = 0; i != _arc_num; ++i) {
1143
          if (_cost[i] > art_cost) art_cost = _cost[i];
1144
        }
1145
        art_cost = (art_cost + 1) * _node_num;
1078
        ART_COST = (ART_COST + 1) * _node_num;
1146 1079
      }
1147 1080

	
1148
      // Run Circulation to check if a feasible solution exists
1149
      typedef ConstMap<Arc, Flow> ConstArcMap;
1150
      ConstArcMap zero_arc_map(0), inf_arc_map(inf_cap);
1151
      FlowNodeMap *csup = NULL;
1152
      bool local_csup = false;
1153
      if (_psupply) {
1154
        csup = _psupply;
1155
      } else {
1156
        csup = new FlowNodeMap(_graph, 0);
1157
        (*csup)[_psource] =  _pstflow;
1158
        (*csup)[_ptarget] = -_pstflow;
1159
        local_csup = true;
1081
      // Initialize arc maps
1082
      for (int i = 0; i != _arc_num; ++i) {
1083
        _flow[i] = 0;
1084
        _state[i] = STATE_LOWER;
1160 1085
      }
1161
      bool circ_result = false;
1162
      if (_ptype == GEQ || (_ptype == LEQ && sum_supply == 0)) {
1163
        // GEQ problem type
1164
        if (_plower) {
1165
          if (_pupper) {
1166
            Circulation<GR, FlowArcMap, FlowArcMap, FlowNodeMap>
1167
              circ(_graph, *_plower, *_pupper, *csup);
1168
            circ_result = circ.run();
1169
          } else {
1170
            Circulation<GR, FlowArcMap, ConstArcMap, FlowNodeMap>
1171
              circ(_graph, *_plower, inf_arc_map, *csup);
1172
            circ_result = circ.run();
1173
          }
1174
        } else {
1175
          if (_pupper) {
1176
            Circulation<GR, ConstArcMap, FlowArcMap, FlowNodeMap>
1177
              circ(_graph, zero_arc_map, *_pupper, *csup);
1178
            circ_result = circ.run();
1179
          } else {
1180
            Circulation<GR, ConstArcMap, ConstArcMap, FlowNodeMap>
1181
              circ(_graph, zero_arc_map, inf_arc_map, *csup);
1182
            circ_result = circ.run();
1183
          }
1184
        }
1185
      } else {
1186
        // LEQ problem type
1187
        typedef ReverseDigraph<const GR> RevGraph;
1188
        typedef NegMap<FlowNodeMap> NegNodeMap;
1189
        RevGraph rgraph(_graph);
1190
        NegNodeMap neg_csup(*csup);
1191
        if (_plower) {
1192
          if (_pupper) {
1193
            Circulation<RevGraph, FlowArcMap, FlowArcMap, NegNodeMap>
1194
              circ(rgraph, *_plower, *_pupper, neg_csup);
1195
            circ_result = circ.run();
1196
          } else {
1197
            Circulation<RevGraph, FlowArcMap, ConstArcMap, NegNodeMap>
1198
              circ(rgraph, *_plower, inf_arc_map, neg_csup);
1199
            circ_result = circ.run();
1200
          }
1201
        } else {
1202
          if (_pupper) {
1203
            Circulation<RevGraph, ConstArcMap, FlowArcMap, NegNodeMap>
1204
              circ(rgraph, zero_arc_map, *_pupper, neg_csup);
1205
            circ_result = circ.run();
1206
          } else {
1207
            Circulation<RevGraph, ConstArcMap, ConstArcMap, NegNodeMap>
1208
              circ(rgraph, zero_arc_map, inf_arc_map, neg_csup);
1209
            circ_result = circ.run();
1210
          }
1211
        }
1212
      }
1213
      if (local_csup) delete csup;
1214
      if (!circ_result) return false;
1215

	
1086
      
1216 1087
      // Set data for the artificial root node
1217 1088
      _root = _node_num;
1218 1089
      _parent[_root] = -1;
1219 1090
      _pred[_root] = -1;
1220 1091
      _thread[_root] = 0;
1221 1092
      _rev_thread[0] = _root;
1222
      _succ_num[_root] = all_node_num;
1093
      _succ_num[_root] = _node_num + 1;
1223 1094
      _last_succ[_root] = _root - 1;
1224
      _supply[_root] = -sum_supply;
1225
      if (sum_supply < 0) {
1226
        _pi[_root] = -art_cost;
1227
      } else {
1228
        _pi[_root] = art_cost;
1229
      }
1230

	
1231
      // Store the arcs in a mixed order
1232
      int k = std::max(int(std::sqrt(double(_arc_num))), 10);
1233
      int i = 0;
1234
      for (ArcIt e(_graph); e != INVALID; ++e) {
1235
        _arc_ref[i] = e;
1236
        if ((i += k) >= _arc_num) i = (i % k) + 1;
1237
      }
1238

	
1239
      // Initialize arc maps
1240
      if (_pupper && _pcost) {
1241
        for (int i = 0; i != _arc_num; ++i) {
1242
          Arc e = _arc_ref[i];
1243
          _source[i] = _node_id[_graph.source(e)];
1244
          _target[i] = _node_id[_graph.target(e)];
1245
          _cap[i] = (*_pupper)[e];
1246
          _cost[i] = (*_pcost)[e];
1247
          _flow[i] = 0;
1248
          _state[i] = STATE_LOWER;
1249
        }
1250
      } else {
1251
        for (int i = 0; i != _arc_num; ++i) {
1252
          Arc e = _arc_ref[i];
1253
          _source[i] = _node_id[_graph.source(e)];
1254
          _target[i] = _node_id[_graph.target(e)];
1255
          _flow[i] = 0;
1256
          _state[i] = STATE_LOWER;
1257
        }
1258
        if (_pupper) {
1259
          for (int i = 0; i != _arc_num; ++i)
1260
            _cap[i] = (*_pupper)[_arc_ref[i]];
1261
        } else {
1262
          for (int i = 0; i != _arc_num; ++i)
1263
            _cap[i] = inf_cap;
1264
        }
1265
        if (_pcost) {
1266
          for (int i = 0; i != _arc_num; ++i)
1267
            _cost[i] = (*_pcost)[_arc_ref[i]];
1268
        } else {
1269
          for (int i = 0; i != _arc_num; ++i)
1270
            _cost[i] = 1;
1271
        }
1272
      }
1273
      
1274
      // Remove non-zero lower bounds
1275
      if (_plower) {
1276
        for (int i = 0; i != _arc_num; ++i) {
1277
          Flow c = (*_plower)[_arc_ref[i]];
1278
          if (c != 0) {
1279
            _cap[i] -= c;
1280
            _supply[_source[i]] -= c;
1281
            _supply[_target[i]] += c;
1282
          }
1283
        }
1284
      }
1095
      _supply[_root] = -_sum_supply;
1096
      _pi[_root] = _sum_supply < 0 ? -ART_COST : ART_COST;
1285 1097

	
1286 1098
      // Add artificial arcs and initialize the spanning tree data structure
1287 1099
      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1100
        _parent[u] = _root;
1101
        _pred[u] = e;
1288 1102
        _thread[u] = u + 1;
1289 1103
        _rev_thread[u + 1] = u;
1290 1104
        _succ_num[u] = 1;
1291 1105
        _last_succ[u] = u;
1292
        _parent[u] = _root;
1293
        _pred[u] = e;
1294
        _cost[e] = art_cost;
1295
        _cap[e] = inf_cap;
1106
        _cost[e] = ART_COST;
1107
        _cap[e] = INF;
1296 1108
        _state[e] = STATE_TREE;
1297
        if (_supply[u] > 0 || (_supply[u] == 0 && sum_supply <= 0)) {
1109
        if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
1298 1110
          _flow[e] = _supply[u];
1299 1111
          _forward[u] = true;
1300
          _pi[u] = -art_cost + _pi[_root];
1112
          _pi[u] = -ART_COST + _pi[_root];
1301 1113
        } else {
1302 1114
          _flow[e] = -_supply[u];
1303 1115
          _forward[u] = false;
1304
          _pi[u] = art_cost + _pi[_root];
1116
          _pi[u] = ART_COST + _pi[_root];
1305 1117
        }
1306 1118
      }
1307 1119

	
1308 1120
      return true;
1309 1121
    }
1310 1122

	
1311 1123
    // Find the join node
1312 1124
    void findJoinNode() {
1313 1125
      int u = _source[in_arc];
1314 1126
      int v = _target[in_arc];
1315 1127
      while (u != v) {
1316 1128
        if (_succ_num[u] < _succ_num[v]) {
1317 1129
          u = _parent[u];
1318 1130
        } else {
1319 1131
          v = _parent[v];
1320 1132
        }
1321 1133
      }
1322 1134
      join = u;
1323 1135
    }
1324 1136

	
1325 1137
    // Find the leaving arc of the cycle and returns true if the
1326 1138
    // leaving arc is not the same as the entering arc
1327 1139
    bool findLeavingArc() {
1328 1140
      // Initialize first and second nodes according to the direction
1329 1141
      // of the cycle
1330 1142
      if (_state[in_arc] == STATE_LOWER) {
1331 1143
        first  = _source[in_arc];
1332 1144
        second = _target[in_arc];
1333 1145
      } else {
1334 1146
        first  = _target[in_arc];
1335 1147
        second = _source[in_arc];
1336 1148
      }
1337 1149
      delta = _cap[in_arc];
1338 1150
      int result = 0;
1339
      Flow d;
1151
      Value d;
1340 1152
      int e;
1341 1153

	
1342 1154
      // Search the cycle along the path form the first node to the root
1343 1155
      for (int u = first; u != join; u = _parent[u]) {
1344 1156
        e = _pred[u];
1345
        d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
1157
        d = _forward[u] ?
1158
          _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1346 1159
        if (d < delta) {
1347 1160
          delta = d;
1348 1161
          u_out = u;
1349 1162
          result = 1;
1350 1163
        }
1351 1164
      }
1352 1165
      // Search the cycle along the path form the second node to the root
1353 1166
      for (int u = second; u != join; u = _parent[u]) {
1354 1167
        e = _pred[u];
1355
        d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
1168
        d = _forward[u] ? 
1169
          (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1356 1170
        if (d <= delta) {
1357 1171
          delta = d;
1358 1172
          u_out = u;
1359 1173
          result = 2;
1360 1174
        }
1361 1175
      }
1362 1176

	
1363 1177
      if (result == 1) {
1364 1178
        u_in = first;
1365 1179
        v_in = second;
1366 1180
      } else {
1367 1181
        u_in = second;
1368 1182
        v_in = first;
1369 1183
      }
1370 1184
      return result != 0;
1371 1185
    }
1372 1186

	
1373 1187
    // Change _flow and _state vectors
1374 1188
    void changeFlow(bool change) {
1375 1189
      // Augment along the cycle
1376 1190
      if (delta > 0) {
1377
        Flow val = _state[in_arc] * delta;
1191
        Value val = _state[in_arc] * delta;
1378 1192
        _flow[in_arc] += val;
1379 1193
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1380 1194
          _flow[_pred[u]] += _forward[u] ? -val : val;
1381 1195
        }
1382 1196
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1383 1197
          _flow[_pred[u]] += _forward[u] ? val : -val;
1384 1198
        }
1385 1199
      }
1386 1200
      // Update the state of the entering and leaving arcs
1387 1201
      if (change) {
1388 1202
        _state[in_arc] = STATE_TREE;
1389 1203
        _state[_pred[u_out]] =
1390 1204
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1391 1205
      } else {
1392 1206
        _state[in_arc] = -_state[in_arc];
1393 1207
      }
1394 1208
    }
1395 1209

	
1396 1210
    // Update the tree structure
1397 1211
    void updateTreeStructure() {
1398 1212
      int u, w;
1399 1213
      int old_rev_thread = _rev_thread[u_out];
1400 1214
      int old_succ_num = _succ_num[u_out];
1401 1215
      int old_last_succ = _last_succ[u_out];
1402 1216
      v_out = _parent[u_out];
1403 1217

	
1404 1218
      u = _last_succ[u_in];  // the last successor of u_in
1405 1219
      right = _thread[u];    // the node after it
1406 1220

	
1407 1221
      // Handle the case when old_rev_thread equals to v_in
1408 1222
      // (it also means that join and v_out coincide)
1409 1223
      if (old_rev_thread == v_in) {
1410 1224
        last = _thread[_last_succ[u_out]];
1411 1225
      } else {
1412 1226
        last = _thread[v_in];
1413 1227
      }
1414 1228

	
1415 1229
      // Update _thread and _parent along the stem nodes (i.e. the nodes
1416 1230
      // between u_in and u_out, whose parent have to be changed)
1417 1231
      _thread[v_in] = stem = u_in;
1418 1232
      _dirty_revs.clear();
1419 1233
      _dirty_revs.push_back(v_in);
1420 1234
      par_stem = v_in;
1421 1235
      while (stem != u_out) {
1422 1236
        // Insert the next stem node into the thread list
1423 1237
        new_stem = _parent[stem];
1424 1238
        _thread[u] = new_stem;
1425 1239
        _dirty_revs.push_back(u);
1426 1240

	
1427 1241
        // Remove the subtree of stem from the thread list
1428 1242
        w = _rev_thread[stem];
1429 1243
        _thread[w] = right;
1430 1244
        _rev_thread[right] = w;
1431 1245

	
1432 1246
        // Change the parent node and shift stem nodes
1433 1247
        _parent[stem] = par_stem;
1434 1248
        par_stem = stem;
1435 1249
        stem = new_stem;
1436 1250

	
1437 1251
        // Update u and right
1438 1252
        u = _last_succ[stem] == _last_succ[par_stem] ?
1439 1253
          _rev_thread[par_stem] : _last_succ[stem];
1440 1254
        right = _thread[u];
1441 1255
      }
1442 1256
      _parent[u_out] = par_stem;
1443 1257
      _thread[u] = last;
1444 1258
      _rev_thread[last] = u;
1445 1259
      _last_succ[u_out] = u;
1446 1260

	
1447 1261
      // Remove the subtree of u_out from the thread list except for
1448 1262
      // the case when old_rev_thread equals to v_in
1449 1263
      // (it also means that join and v_out coincide)
1450 1264
      if (old_rev_thread != v_in) {
1451 1265
        _thread[old_rev_thread] = right;
1452 1266
        _rev_thread[right] = old_rev_thread;
1453 1267
      }
1454 1268

	
1455 1269
      // Update _rev_thread using the new _thread values
1456 1270
      for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1457 1271
        u = _dirty_revs[i];
1458 1272
        _rev_thread[_thread[u]] = u;
1459 1273
      }
1460 1274

	
1461 1275
      // Update _pred, _forward, _last_succ and _succ_num for the
1462 1276
      // stem nodes from u_out to u_in
1463 1277
      int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1464 1278
      u = u_out;
1465 1279
      while (u != u_in) {
1466 1280
        w = _parent[u];
1467 1281
        _pred[u] = _pred[w];
1468 1282
        _forward[u] = !_forward[w];
1469 1283
        tmp_sc += _succ_num[u] - _succ_num[w];
1470 1284
        _succ_num[u] = tmp_sc;
1471 1285
        _last_succ[w] = tmp_ls;
1472 1286
        u = w;
1473 1287
      }
1474 1288
      _pred[u_in] = in_arc;
1475 1289
      _forward[u_in] = (u_in == _source[in_arc]);
1476 1290
      _succ_num[u_in] = old_succ_num;
1477 1291

	
1478 1292
      // Set limits for updating _last_succ form v_in and v_out
1479 1293
      // towards the root
1480 1294
      int up_limit_in = -1;
1481 1295
      int up_limit_out = -1;
1482 1296
      if (_last_succ[join] == v_in) {
1483 1297
        up_limit_out = join;
1484 1298
      } else {
1485 1299
        up_limit_in = join;
1486 1300
      }
1487 1301

	
1488 1302
      // Update _last_succ from v_in towards the root
1489 1303
      for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1490 1304
           u = _parent[u]) {
1491 1305
        _last_succ[u] = _last_succ[u_out];
1492 1306
      }
1493 1307
      // Update _last_succ from v_out towards the root
1494 1308
      if (join != old_rev_thread && v_in != old_rev_thread) {
1495 1309
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1496 1310
             u = _parent[u]) {
1497 1311
          _last_succ[u] = old_rev_thread;
1498 1312
        }
1499 1313
      } else {
1500 1314
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1501 1315
             u = _parent[u]) {
1502 1316
          _last_succ[u] = _last_succ[u_out];
1503 1317
        }
1504 1318
      }
1505 1319

	
1506 1320
      // Update _succ_num from v_in to join
1507 1321
      for (u = v_in; u != join; u = _parent[u]) {
1508 1322
        _succ_num[u] += old_succ_num;
1509 1323
      }
1510 1324
      // Update _succ_num from v_out to join
1511 1325
      for (u = v_out; u != join; u = _parent[u]) {
1512 1326
        _succ_num[u] -= old_succ_num;
1513 1327
      }
1514 1328
    }
1515 1329

	
1516 1330
    // Update potentials
1517 1331
    void updatePotential() {
1518 1332
      Cost sigma = _forward[u_in] ?
1519 1333
        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1520 1334
        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1521 1335
      // Update potentials in the subtree, which has been moved
1522 1336
      int end = _thread[_last_succ[u_in]];
1523 1337
      for (int u = u_in; u != end; u = _thread[u]) {
1524 1338
        _pi[u] += sigma;
1525 1339
      }
1526 1340
    }
1527 1341

	
1528 1342
    // Execute the algorithm
1529
    bool start(PivotRule pivot_rule) {
1343
    ProblemType start(PivotRule pivot_rule) {
1530 1344
      // Select the pivot rule implementation
1531 1345
      switch (pivot_rule) {
1532 1346
        case FIRST_ELIGIBLE:
1533 1347
          return start<FirstEligiblePivotRule>();
1534 1348
        case BEST_ELIGIBLE:
1535 1349
          return start<BestEligiblePivotRule>();
1536 1350
        case BLOCK_SEARCH:
1537 1351
          return start<BlockSearchPivotRule>();
1538 1352
        case CANDIDATE_LIST:
1539 1353
          return start<CandidateListPivotRule>();
1540 1354
        case ALTERING_LIST:
1541 1355
          return start<AlteringListPivotRule>();
1542 1356
      }
1543
      return false;
1357
      return INFEASIBLE; // avoid warning
1544 1358
    }
1545 1359

	
1546 1360
    template <typename PivotRuleImpl>
1547
    bool start() {
1361
    ProblemType start() {
1548 1362
      PivotRuleImpl pivot(*this);
1549 1363

	
1550 1364
      // Execute the Network Simplex algorithm
1551 1365
      while (pivot.findEnteringArc()) {
1552 1366
        findJoinNode();
1553 1367
        bool change = findLeavingArc();
1368
        if (delta >= INF) return UNBOUNDED;
1554 1369
        changeFlow(change);
1555 1370
        if (change) {
1556 1371
          updateTreeStructure();
1557 1372
          updatePotential();
1558 1373
        }
1559 1374
      }
1560

	
1561
      // Copy flow values to _flow_map
1562
      if (_plower) {
1563
        for (int i = 0; i != _arc_num; ++i) {
1564
          Arc e = _arc_ref[i];
1565
          _flow_map->set(e, (*_plower)[e] + _flow[i]);
1566
        }
1567
      } else {
1568
        for (int i = 0; i != _arc_num; ++i) {
1569
          _flow_map->set(_arc_ref[i], _flow[i]);
1375
      
1376
      // Check feasibility
1377
      if (_sum_supply < 0) {
1378
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1379
          if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
1570 1380
        }
1571 1381
      }
1572
      // Copy potential values to _potential_map
1573
      for (NodeIt n(_graph); n != INVALID; ++n) {
1574
        _potential_map->set(n, _pi[_node_id[n]]);
1382
      else if (_sum_supply > 0) {
1383
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1384
          if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
1385
        }
1386
      }
1387
      else {
1388
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1389
          if (_flow[e] != 0) return INFEASIBLE;
1390
        }
1575 1391
      }
1576 1392

	
1577
      return true;
1393
      // Transform the solution and the supply map to the original form
1394
      if (_have_lower) {
1395
        for (int i = 0; i != _arc_num; ++i) {
1396
          Value c = _lower[i];
1397
          if (c != 0) {
1398
            _flow[i] += c;
1399
            _supply[_source[i]] += c;
1400
            _supply[_target[i]] -= c;
1401
          }
1402
        }
1403
      }
1404

	
1405
      return OPTIMAL;
1578 1406
    }
1579 1407

	
1580 1408
  }; //class NetworkSimplex
1581 1409

	
1582 1410
  ///@}
1583 1411

	
1584 1412
} //namespace lemon
1585 1413

	
1586 1414
#endif //LEMON_NETWORK_SIMPLEX_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_PREFLOW_H
20 20
#define LEMON_PREFLOW_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24

	
25 25
/// \file
26 26
/// \ingroup max_flow
27 27
/// \brief Implementation of the preflow algorithm.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  /// \brief Default traits class of Preflow class.
32 32
  ///
33 33
  /// Default traits class of Preflow class.
34 34
  /// \tparam GR Digraph type.
35 35
  /// \tparam CAP Capacity map type.
36 36
  template <typename GR, typename CAP>
37 37
  struct PreflowDefaultTraits {
38 38

	
39 39
    /// \brief The type of the digraph the algorithm runs on.
40 40
    typedef GR Digraph;
41 41

	
42 42
    /// \brief The type of the map that stores the arc capacities.
43 43
    ///
44 44
    /// The type of the map that stores the arc capacities.
45 45
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
46 46
    typedef CAP CapacityMap;
47 47

	
48 48
    /// \brief The type of the flow values.
49
    typedef typename CapacityMap::Value Flow;
49
    typedef typename CapacityMap::Value Value;
50 50

	
51 51
    /// \brief The type of the map that stores the flow values.
52 52
    ///
53 53
    /// The type of the map that stores the flow values.
54 54
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
55
    typedef typename Digraph::template ArcMap<Flow> FlowMap;
55
    typedef typename Digraph::template ArcMap<Value> FlowMap;
56 56

	
57 57
    /// \brief Instantiates a FlowMap.
58 58
    ///
59 59
    /// This function instantiates a \ref FlowMap.
60 60
    /// \param digraph The digraph for which we would like to define
61 61
    /// the flow map.
62 62
    static FlowMap* createFlowMap(const Digraph& digraph) {
63 63
      return new FlowMap(digraph);
64 64
    }
65 65

	
66 66
    /// \brief The elevator type used by Preflow algorithm.
67 67
    ///
68 68
    /// The elevator type used by Preflow algorithm.
69 69
    ///
70 70
    /// \sa Elevator
71 71
    /// \sa LinkedElevator
72 72
    typedef LinkedElevator<Digraph, typename Digraph::Node> Elevator;
73 73

	
74 74
    /// \brief Instantiates an Elevator.
75 75
    ///
76 76
    /// This function instantiates an \ref Elevator.
77 77
    /// \param digraph The digraph for which we would like to define
78 78
    /// the elevator.
79 79
    /// \param max_level The maximum level of the elevator.
80 80
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
81 81
      return new Elevator(digraph, max_level);
82 82
    }
83 83

	
84 84
    /// \brief The tolerance used by the algorithm
85 85
    ///
86 86
    /// The tolerance used by the algorithm to handle inexact computation.
87
    typedef lemon::Tolerance<Flow> Tolerance;
87
    typedef lemon::Tolerance<Value> Tolerance;
88 88

	
89 89
  };
90 90

	
91 91

	
92 92
  /// \ingroup max_flow
93 93
  ///
94 94
  /// \brief %Preflow algorithm class.
95 95
  ///
96 96
  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
97 97
  /// \e push-relabel algorithm producing a \ref max_flow
98 98
  /// "flow of maximum value" in a digraph.
99 99
  /// The preflow algorithms are the fastest known maximum
100 100
  /// flow algorithms. The current implementation use a mixture of the
101 101
  /// \e "highest label" and the \e "bound decrease" heuristics.
102 102
  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
103 103
  ///
104 104
  /// The algorithm consists of two phases. After the first phase
105 105
  /// the maximum flow value and the minimum cut is obtained. The
106 106
  /// second phase constructs a feasible maximum flow on each arc.
107 107
  ///
108 108
  /// \tparam GR The type of the digraph the algorithm runs on.
109 109
  /// \tparam CAP The type of the capacity map. The default map
110 110
  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
111 111
#ifdef DOXYGEN
112 112
  template <typename GR, typename CAP, typename TR>
113 113
#else
114 114
  template <typename GR,
115 115
            typename CAP = typename GR::template ArcMap<int>,
116 116
            typename TR = PreflowDefaultTraits<GR, CAP> >
117 117
#endif
118 118
  class Preflow {
119 119
  public:
120 120

	
121 121
    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
122 122
    typedef TR Traits;
123 123
    ///The type of the digraph the algorithm runs on.
124 124
    typedef typename Traits::Digraph Digraph;
125 125
    ///The type of the capacity map.
126 126
    typedef typename Traits::CapacityMap CapacityMap;
127 127
    ///The type of the flow values.
128
    typedef typename Traits::Flow Flow;
128
    typedef typename Traits::Value Value;
129 129

	
130 130
    ///The type of the flow map.
131 131
    typedef typename Traits::FlowMap FlowMap;
132 132
    ///The type of the elevator.
133 133
    typedef typename Traits::Elevator Elevator;
134 134
    ///The type of the tolerance.
135 135
    typedef typename Traits::Tolerance Tolerance;
136 136

	
137 137
  private:
138 138

	
139 139
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
140 140

	
141 141
    const Digraph& _graph;
142 142
    const CapacityMap* _capacity;
143 143

	
144 144
    int _node_num;
145 145

	
146 146
    Node _source, _target;
147 147

	
148 148
    FlowMap* _flow;
149 149
    bool _local_flow;
150 150

	
151 151
    Elevator* _level;
152 152
    bool _local_level;
153 153

	
154
    typedef typename Digraph::template NodeMap<Flow> ExcessMap;
154
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
155 155
    ExcessMap* _excess;
156 156

	
157 157
    Tolerance _tolerance;
158 158

	
159 159
    bool _phase;
160 160

	
161 161

	
162 162
    void createStructures() {
163 163
      _node_num = countNodes(_graph);
164 164

	
165 165
      if (!_flow) {
166 166
        _flow = Traits::createFlowMap(_graph);
167 167
        _local_flow = true;
168 168
      }
169 169
      if (!_level) {
170 170
        _level = Traits::createElevator(_graph, _node_num);
171 171
        _local_level = true;
172 172
      }
173 173
      if (!_excess) {
174 174
        _excess = new ExcessMap(_graph);
175 175
      }
176 176
    }
177 177

	
178 178
    void destroyStructures() {
179 179
      if (_local_flow) {
180 180
        delete _flow;
181 181
      }
182 182
      if (_local_level) {
183 183
        delete _level;
184 184
      }
185 185
      if (_excess) {
186 186
        delete _excess;
187 187
      }
188 188
    }
189 189

	
190 190
  public:
191 191

	
192 192
    typedef Preflow Create;
193 193

	
194 194
    ///\name Named Template Parameters
195 195

	
196 196
    ///@{
197 197

	
198 198
    template <typename T>
199 199
    struct SetFlowMapTraits : public Traits {
200 200
      typedef T FlowMap;
201 201
      static FlowMap *createFlowMap(const Digraph&) {
202 202
        LEMON_ASSERT(false, "FlowMap is not initialized");
203 203
        return 0; // ignore warnings
204 204
      }
205 205
    };
206 206

	
207 207
    /// \brief \ref named-templ-param "Named parameter" for setting
208 208
    /// FlowMap type
209 209
    ///
210 210
    /// \ref named-templ-param "Named parameter" for setting FlowMap
211 211
    /// type.
212 212
    template <typename T>
213 213
    struct SetFlowMap
214 214
      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
215 215
      typedef Preflow<Digraph, CapacityMap,
216 216
                      SetFlowMapTraits<T> > Create;
217 217
    };
218 218

	
219 219
    template <typename T>
220 220
    struct SetElevatorTraits : public Traits {
221 221
      typedef T Elevator;
222 222
      static Elevator *createElevator(const Digraph&, int) {
223 223
        LEMON_ASSERT(false, "Elevator is not initialized");
224 224
        return 0; // ignore warnings
225 225
      }
226 226
    };
227 227

	
228 228
    /// \brief \ref named-templ-param "Named parameter" for setting
229 229
    /// Elevator type
230 230
    ///
231 231
    /// \ref named-templ-param "Named parameter" for setting Elevator
232 232
    /// type. If this named parameter is used, then an external
233 233
    /// elevator object must be passed to the algorithm using the
234 234
    /// \ref elevator(Elevator&) "elevator()" function before calling
235 235
    /// \ref run() or \ref init().
236 236
    /// \sa SetStandardElevator
237 237
    template <typename T>
238 238
    struct SetElevator
239 239
      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
240 240
      typedef Preflow<Digraph, CapacityMap,
241 241
                      SetElevatorTraits<T> > Create;
242 242
    };
243 243

	
244 244
    template <typename T>
245 245
    struct SetStandardElevatorTraits : public Traits {
246 246
      typedef T Elevator;
247 247
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
248 248
        return new Elevator(digraph, max_level);
249 249
      }
250 250
    };
251 251

	
252 252
    /// \brief \ref named-templ-param "Named parameter" for setting
253 253
    /// Elevator type with automatic allocation
254 254
    ///
255 255
    /// \ref named-templ-param "Named parameter" for setting Elevator
256 256
    /// type with automatic allocation.
257 257
    /// The Elevator should have standard constructor interface to be
258 258
    /// able to automatically created by the algorithm (i.e. the
259 259
    /// digraph and the maximum level should be passed to it).
260 260
    /// However an external elevator object could also be passed to the
261 261
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
262 262
    /// before calling \ref run() or \ref init().
263 263
    /// \sa SetElevator
264 264
    template <typename T>
265 265
    struct SetStandardElevator
266 266
      : public Preflow<Digraph, CapacityMap,
267 267
                       SetStandardElevatorTraits<T> > {
268 268
      typedef Preflow<Digraph, CapacityMap,
269 269
                      SetStandardElevatorTraits<T> > Create;
270 270
    };
271 271

	
272 272
    /// @}
273 273

	
274 274
  protected:
275 275

	
276 276
    Preflow() {}
277 277

	
278 278
  public:
279 279

	
280 280

	
281 281
    /// \brief The constructor of the class.
282 282
    ///
283 283
    /// The constructor of the class.
284 284
    /// \param digraph The digraph the algorithm runs on.
285 285
    /// \param capacity The capacity of the arcs.
286 286
    /// \param source The source node.
287 287
    /// \param target The target node.
288 288
    Preflow(const Digraph& digraph, const CapacityMap& capacity,
289 289
            Node source, Node target)
290 290
      : _graph(digraph), _capacity(&capacity),
291 291
        _node_num(0), _source(source), _target(target),
292 292
        _flow(0), _local_flow(false),
293 293
        _level(0), _local_level(false),
294 294
        _excess(0), _tolerance(), _phase() {}
295 295

	
296 296
    /// \brief Destructor.
297 297
    ///
298 298
    /// Destructor.
299 299
    ~Preflow() {
300 300
      destroyStructures();
301 301
    }
302 302

	
303 303
    /// \brief Sets the capacity map.
304 304
    ///
305 305
    /// Sets the capacity map.
306 306
    /// \return <tt>(*this)</tt>
307 307
    Preflow& capacityMap(const CapacityMap& map) {
308 308
      _capacity = &map;
309 309
      return *this;
310 310
    }
311 311

	
312 312
    /// \brief Sets the flow map.
313 313
    ///
314 314
    /// Sets the flow map.
315 315
    /// If you don't use this function before calling \ref run() or
316 316
    /// \ref init(), an instance will be allocated automatically.
317 317
    /// The destructor deallocates this automatically allocated map,
318 318
    /// of course.
319 319
    /// \return <tt>(*this)</tt>
320 320
    Preflow& flowMap(FlowMap& map) {
321 321
      if (_local_flow) {
322 322
        delete _flow;
323 323
        _local_flow = false;
324 324
      }
325 325
      _flow = &map;
326 326
      return *this;
327 327
    }
328 328

	
329 329
    /// \brief Sets the source node.
330 330
    ///
331 331
    /// Sets the source node.
332 332
    /// \return <tt>(*this)</tt>
333 333
    Preflow& source(const Node& node) {
334 334
      _source = node;
335 335
      return *this;
336 336
    }
337 337

	
338 338
    /// \brief Sets the target node.
339 339
    ///
340 340
    /// Sets the target node.
341 341
    /// \return <tt>(*this)</tt>
342 342
    Preflow& target(const Node& node) {
343 343
      _target = node;
344 344
      return *this;
345 345
    }
346 346

	
347 347
    /// \brief Sets the elevator used by algorithm.
348 348
    ///
349 349
    /// Sets the elevator used by algorithm.
350 350
    /// If you don't use this function before calling \ref run() or
351 351
    /// \ref init(), an instance will be allocated automatically.
352 352
    /// The destructor deallocates this automatically allocated elevator,
353 353
    /// of course.
354 354
    /// \return <tt>(*this)</tt>
355 355
    Preflow& elevator(Elevator& elevator) {
356 356
      if (_local_level) {
357 357
        delete _level;
358 358
        _local_level = false;
359 359
      }
360 360
      _level = &elevator;
361 361
      return *this;
362 362
    }
363 363

	
364 364
    /// \brief Returns a const reference to the elevator.
365 365
    ///
366 366
    /// Returns a const reference to the elevator.
367 367
    ///
368 368
    /// \pre Either \ref run() or \ref init() must be called before
369 369
    /// using this function.
370 370
    const Elevator& elevator() const {
371 371
      return *_level;
372 372
    }
373 373

	
374 374
    /// \brief Sets the tolerance used by algorithm.
375 375
    ///
376 376
    /// Sets the tolerance used by algorithm.
377 377
    Preflow& tolerance(const Tolerance& tolerance) const {
378 378
      _tolerance = tolerance;
379 379
      return *this;
380 380
    }
381 381

	
382 382
    /// \brief Returns a const reference to the tolerance.
383 383
    ///
384 384
    /// Returns a const reference to the tolerance.
385 385
    const Tolerance& tolerance() const {
386 386
      return tolerance;
387 387
    }
388 388

	
389 389
    /// \name Execution Control
390 390
    /// The simplest way to execute the preflow algorithm is to use
391 391
    /// \ref run() or \ref runMinCut().\n
392 392
    /// If you need more control on the initial solution or the execution,
393 393
    /// first you have to call one of the \ref init() functions, then
394 394
    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
395 395

	
396 396
    ///@{
397 397

	
398 398
    /// \brief Initializes the internal data structures.
399 399
    ///
400 400
    /// Initializes the internal data structures and sets the initial
401 401
    /// flow to zero on each arc.
402 402
    void init() {
403 403
      createStructures();
404 404

	
405 405
      _phase = true;
406 406
      for (NodeIt n(_graph); n != INVALID; ++n) {
407 407
        (*_excess)[n] = 0;
408 408
      }
409 409

	
410 410
      for (ArcIt e(_graph); e != INVALID; ++e) {
411 411
        _flow->set(e, 0);
412 412
      }
413 413

	
414 414
      typename Digraph::template NodeMap<bool> reached(_graph, false);
415 415

	
416 416
      _level->initStart();
417 417
      _level->initAddItem(_target);
418 418

	
419 419
      std::vector<Node> queue;
420 420
      reached[_source] = true;
421 421

	
422 422
      queue.push_back(_target);
423 423
      reached[_target] = true;
424 424
      while (!queue.empty()) {
425 425
        _level->initNewLevel();
426 426
        std::vector<Node> nqueue;
427 427
        for (int i = 0; i < int(queue.size()); ++i) {
428 428
          Node n = queue[i];
429 429
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
430 430
            Node u = _graph.source(e);
431 431
            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
432 432
              reached[u] = true;
433 433
              _level->initAddItem(u);
434 434
              nqueue.push_back(u);
435 435
            }
436 436
          }
437 437
        }
438 438
        queue.swap(nqueue);
439 439
      }
440 440
      _level->initFinish();
441 441

	
442 442
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
443 443
        if (_tolerance.positive((*_capacity)[e])) {
444 444
          Node u = _graph.target(e);
445 445
          if ((*_level)[u] == _level->maxLevel()) continue;
446 446
          _flow->set(e, (*_capacity)[e]);
447 447
          (*_excess)[u] += (*_capacity)[e];
448 448
          if (u != _target && !_level->active(u)) {
449 449
            _level->activate(u);
450 450
          }
451 451
        }
452 452
      }
453 453
    }
454 454

	
455 455
    /// \brief Initializes the internal data structures using the
456 456
    /// given flow map.
457 457
    ///
458 458
    /// Initializes the internal data structures and sets the initial
459 459
    /// flow to the given \c flowMap. The \c flowMap should contain a
460 460
    /// flow or at least a preflow, i.e. at each node excluding the
461 461
    /// source node the incoming flow should greater or equal to the
462 462
    /// outgoing flow.
463 463
    /// \return \c false if the given \c flowMap is not a preflow.
464 464
    template <typename FlowMap>
465 465
    bool init(const FlowMap& flowMap) {
466 466
      createStructures();
467 467

	
468 468
      for (ArcIt e(_graph); e != INVALID; ++e) {
469 469
        _flow->set(e, flowMap[e]);
470 470
      }
471 471

	
472 472
      for (NodeIt n(_graph); n != INVALID; ++n) {
473
        Flow excess = 0;
473
        Value excess = 0;
474 474
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
475 475
          excess += (*_flow)[e];
476 476
        }
477 477
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
478 478
          excess -= (*_flow)[e];
479 479
        }
480 480
        if (excess < 0 && n != _source) return false;
481 481
        (*_excess)[n] = excess;
482 482
      }
483 483

	
484 484
      typename Digraph::template NodeMap<bool> reached(_graph, false);
485 485

	
486 486
      _level->initStart();
487 487
      _level->initAddItem(_target);
488 488

	
489 489
      std::vector<Node> queue;
490 490
      reached[_source] = true;
491 491

	
492 492
      queue.push_back(_target);
493 493
      reached[_target] = true;
494 494
      while (!queue.empty()) {
495 495
        _level->initNewLevel();
496 496
        std::vector<Node> nqueue;
497 497
        for (int i = 0; i < int(queue.size()); ++i) {
498 498
          Node n = queue[i];
499 499
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
500 500
            Node u = _graph.source(e);
501 501
            if (!reached[u] &&
502 502
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
503 503
              reached[u] = true;
504 504
              _level->initAddItem(u);
505 505
              nqueue.push_back(u);
506 506
            }
507 507
          }
508 508
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
509 509
            Node v = _graph.target(e);
510 510
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
511 511
              reached[v] = true;
512 512
              _level->initAddItem(v);
513 513
              nqueue.push_back(v);
514 514
            }
515 515
          }
516 516
        }
517 517
        queue.swap(nqueue);
518 518
      }
519 519
      _level->initFinish();
520 520

	
521 521
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
522
        Flow rem = (*_capacity)[e] - (*_flow)[e];
522
        Value rem = (*_capacity)[e] - (*_flow)[e];
523 523
        if (_tolerance.positive(rem)) {
524 524
          Node u = _graph.target(e);
525 525
          if ((*_level)[u] == _level->maxLevel()) continue;
526 526
          _flow->set(e, (*_capacity)[e]);
527 527
          (*_excess)[u] += rem;
528 528
          if (u != _target && !_level->active(u)) {
529 529
            _level->activate(u);
530 530
          }
531 531
        }
532 532
      }
533 533
      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
534
        Flow rem = (*_flow)[e];
534
        Value rem = (*_flow)[e];
535 535
        if (_tolerance.positive(rem)) {
536 536
          Node v = _graph.source(e);
537 537
          if ((*_level)[v] == _level->maxLevel()) continue;
538 538
          _flow->set(e, 0);
539 539
          (*_excess)[v] += rem;
540 540
          if (v != _target && !_level->active(v)) {
541 541
            _level->activate(v);
542 542
          }
543 543
        }
544 544
      }
545 545
      return true;
546 546
    }
547 547

	
548 548
    /// \brief Starts the first phase of the preflow algorithm.
549 549
    ///
550 550
    /// The preflow algorithm consists of two phases, this method runs
551 551
    /// the first phase. After the first phase the maximum flow value
552 552
    /// and a minimum value cut can already be computed, although a
553 553
    /// maximum flow is not yet obtained. So after calling this method
554 554
    /// \ref flowValue() returns the value of a maximum flow and \ref
555 555
    /// minCut() returns a minimum cut.
556 556
    /// \pre One of the \ref init() functions must be called before
557 557
    /// using this function.
558 558
    void startFirstPhase() {
559 559
      _phase = true;
560 560

	
561 561
      Node n = _level->highestActive();
562 562
      int level = _level->highestActiveLevel();
563 563
      while (n != INVALID) {
564 564
        int num = _node_num;
565 565

	
566 566
        while (num > 0 && n != INVALID) {
567
          Flow excess = (*_excess)[n];
567
          Value excess = (*_excess)[n];
568 568
          int new_level = _level->maxLevel();
569 569

	
570 570
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
571
            Flow rem = (*_capacity)[e] - (*_flow)[e];
571
            Value rem = (*_capacity)[e] - (*_flow)[e];
572 572
            if (!_tolerance.positive(rem)) continue;
573 573
            Node v = _graph.target(e);
574 574
            if ((*_level)[v] < level) {
575 575
              if (!_level->active(v) && v != _target) {
576 576
                _level->activate(v);
577 577
              }
578 578
              if (!_tolerance.less(rem, excess)) {
579 579
                _flow->set(e, (*_flow)[e] + excess);
580 580
                (*_excess)[v] += excess;
581 581
                excess = 0;
582 582
                goto no_more_push_1;
583 583
              } else {
584 584
                excess -= rem;
585 585
                (*_excess)[v] += rem;
586 586
                _flow->set(e, (*_capacity)[e]);
587 587
              }
588 588
            } else if (new_level > (*_level)[v]) {
589 589
              new_level = (*_level)[v];
590 590
            }
591 591
          }
592 592

	
593 593
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
594
            Flow rem = (*_flow)[e];
594
            Value rem = (*_flow)[e];
595 595
            if (!_tolerance.positive(rem)) continue;
596 596
            Node v = _graph.source(e);
597 597
            if ((*_level)[v] < level) {
598 598
              if (!_level->active(v) && v != _target) {
599 599
                _level->activate(v);
600 600
              }
601 601
              if (!_tolerance.less(rem, excess)) {
602 602
                _flow->set(e, (*_flow)[e] - excess);
603 603
                (*_excess)[v] += excess;
604 604
                excess = 0;
605 605
                goto no_more_push_1;
606 606
              } else {
607 607
                excess -= rem;
608 608
                (*_excess)[v] += rem;
609 609
                _flow->set(e, 0);
610 610
              }
611 611
            } else if (new_level > (*_level)[v]) {
612 612
              new_level = (*_level)[v];
613 613
            }
614 614
          }
615 615

	
616 616
        no_more_push_1:
617 617

	
618 618
          (*_excess)[n] = excess;
619 619

	
620 620
          if (excess != 0) {
621 621
            if (new_level + 1 < _level->maxLevel()) {
622 622
              _level->liftHighestActive(new_level + 1);
623 623
            } else {
624 624
              _level->liftHighestActiveToTop();
625 625
            }
626 626
            if (_level->emptyLevel(level)) {
627 627
              _level->liftToTop(level);
628 628
            }
629 629
          } else {
630 630
            _level->deactivate(n);
631 631
          }
632 632

	
633 633
          n = _level->highestActive();
634 634
          level = _level->highestActiveLevel();
635 635
          --num;
636 636
        }
637 637

	
638 638
        num = _node_num * 20;
639 639
        while (num > 0 && n != INVALID) {
640
          Flow excess = (*_excess)[n];
640
          Value excess = (*_excess)[n];
641 641
          int new_level = _level->maxLevel();
642 642

	
643 643
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
644
            Flow rem = (*_capacity)[e] - (*_flow)[e];
644
            Value rem = (*_capacity)[e] - (*_flow)[e];
645 645
            if (!_tolerance.positive(rem)) continue;
646 646
            Node v = _graph.target(e);
647 647
            if ((*_level)[v] < level) {
648 648
              if (!_level->active(v) && v != _target) {
649 649
                _level->activate(v);
650 650
              }
651 651
              if (!_tolerance.less(rem, excess)) {
652 652
                _flow->set(e, (*_flow)[e] + excess);
653 653
                (*_excess)[v] += excess;
654 654
                excess = 0;
655 655
                goto no_more_push_2;
656 656
              } else {
657 657
                excess -= rem;
658 658
                (*_excess)[v] += rem;
659 659
                _flow->set(e, (*_capacity)[e]);
660 660
              }
661 661
            } else if (new_level > (*_level)[v]) {
662 662
              new_level = (*_level)[v];
663 663
            }
664 664
          }
665 665

	
666 666
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
667
            Flow rem = (*_flow)[e];
667
            Value rem = (*_flow)[e];
668 668
            if (!_tolerance.positive(rem)) continue;
669 669
            Node v = _graph.source(e);
670 670
            if ((*_level)[v] < level) {
671 671
              if (!_level->active(v) && v != _target) {
672 672
                _level->activate(v);
673 673
              }
674 674
              if (!_tolerance.less(rem, excess)) {
675 675
                _flow->set(e, (*_flow)[e] - excess);
676 676
                (*_excess)[v] += excess;
677 677
                excess = 0;
678 678
                goto no_more_push_2;
679 679
              } else {
680 680
                excess -= rem;
681 681
                (*_excess)[v] += rem;
682 682
                _flow->set(e, 0);
683 683
              }
684 684
            } else if (new_level > (*_level)[v]) {
685 685
              new_level = (*_level)[v];
686 686
            }
687 687
          }
688 688

	
689 689
        no_more_push_2:
690 690

	
691 691
          (*_excess)[n] = excess;
692 692

	
693 693
          if (excess != 0) {
694 694
            if (new_level + 1 < _level->maxLevel()) {
695 695
              _level->liftActiveOn(level, new_level + 1);
696 696
            } else {
697 697
              _level->liftActiveToTop(level);
698 698
            }
699 699
            if (_level->emptyLevel(level)) {
700 700
              _level->liftToTop(level);
701 701
            }
702 702
          } else {
703 703
            _level->deactivate(n);
704 704
          }
705 705

	
706 706
          while (level >= 0 && _level->activeFree(level)) {
707 707
            --level;
708 708
          }
709 709
          if (level == -1) {
710 710
            n = _level->highestActive();
711 711
            level = _level->highestActiveLevel();
712 712
          } else {
713 713
            n = _level->activeOn(level);
714 714
          }
715 715
          --num;
716 716
        }
717 717
      }
718 718
    }
719 719

	
720 720
    /// \brief Starts the second phase of the preflow algorithm.
721 721
    ///
722 722
    /// The preflow algorithm consists of two phases, this method runs
723 723
    /// the second phase. After calling one of the \ref init() functions
724 724
    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
725 725
    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
726 726
    /// value of a maximum flow, \ref minCut() returns a minimum cut
727 727
    /// \pre One of the \ref init() functions and \ref startFirstPhase()
728 728
    /// must be called before using this function.
729 729
    void startSecondPhase() {
730 730
      _phase = false;
731 731

	
732 732
      typename Digraph::template NodeMap<bool> reached(_graph);
733 733
      for (NodeIt n(_graph); n != INVALID; ++n) {
734 734
        reached[n] = (*_level)[n] < _level->maxLevel();
735 735
      }
736 736

	
737 737
      _level->initStart();
738 738
      _level->initAddItem(_source);
739 739

	
740 740
      std::vector<Node> queue;
741 741
      queue.push_back(_source);
742 742
      reached[_source] = true;
743 743

	
744 744
      while (!queue.empty()) {
745 745
        _level->initNewLevel();
746 746
        std::vector<Node> nqueue;
747 747
        for (int i = 0; i < int(queue.size()); ++i) {
748 748
          Node n = queue[i];
749 749
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
750 750
            Node v = _graph.target(e);
751 751
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
752 752
              reached[v] = true;
753 753
              _level->initAddItem(v);
754 754
              nqueue.push_back(v);
755 755
            }
756 756
          }
757 757
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
758 758
            Node u = _graph.source(e);
759 759
            if (!reached[u] &&
760 760
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
761 761
              reached[u] = true;
762 762
              _level->initAddItem(u);
763 763
              nqueue.push_back(u);
764 764
            }
765 765
          }
766 766
        }
767 767
        queue.swap(nqueue);
768 768
      }
769 769
      _level->initFinish();
770 770

	
771 771
      for (NodeIt n(_graph); n != INVALID; ++n) {
772 772
        if (!reached[n]) {
773 773
          _level->dirtyTopButOne(n);
774 774
        } else if ((*_excess)[n] > 0 && _target != n) {
775 775
          _level->activate(n);
776 776
        }
777 777
      }
778 778

	
779 779
      Node n;
780 780
      while ((n = _level->highestActive()) != INVALID) {
781
        Flow excess = (*_excess)[n];
781
        Value excess = (*_excess)[n];
782 782
        int level = _level->highestActiveLevel();
783 783
        int new_level = _level->maxLevel();
784 784

	
785 785
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
786
          Flow rem = (*_capacity)[e] - (*_flow)[e];
786
          Value rem = (*_capacity)[e] - (*_flow)[e];
787 787
          if (!_tolerance.positive(rem)) continue;
788 788
          Node v = _graph.target(e);
789 789
          if ((*_level)[v] < level) {
790 790
            if (!_level->active(v) && v != _source) {
791 791
              _level->activate(v);
792 792
            }
793 793
            if (!_tolerance.less(rem, excess)) {
794 794
              _flow->set(e, (*_flow)[e] + excess);
795 795
              (*_excess)[v] += excess;
796 796
              excess = 0;
797 797
              goto no_more_push;
798 798
            } else {
799 799
              excess -= rem;
800 800
              (*_excess)[v] += rem;
801 801
              _flow->set(e, (*_capacity)[e]);
802 802
            }
803 803
          } else if (new_level > (*_level)[v]) {
804 804
            new_level = (*_level)[v];
805 805
          }
806 806
        }
807 807

	
808 808
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
809
          Flow rem = (*_flow)[e];
809
          Value rem = (*_flow)[e];
810 810
          if (!_tolerance.positive(rem)) continue;
811 811
          Node v = _graph.source(e);
812 812
          if ((*_level)[v] < level) {
813 813
            if (!_level->active(v) && v != _source) {
814 814
              _level->activate(v);
815 815
            }
816 816
            if (!_tolerance.less(rem, excess)) {
817 817
              _flow->set(e, (*_flow)[e] - excess);
818 818
              (*_excess)[v] += excess;
819 819
              excess = 0;
820 820
              goto no_more_push;
821 821
            } else {
822 822
              excess -= rem;
823 823
              (*_excess)[v] += rem;
824 824
              _flow->set(e, 0);
825 825
            }
826 826
          } else if (new_level > (*_level)[v]) {
827 827
            new_level = (*_level)[v];
828 828
          }
829 829
        }
830 830

	
831 831
      no_more_push:
832 832

	
833 833
        (*_excess)[n] = excess;
834 834

	
835 835
        if (excess != 0) {
836 836
          if (new_level + 1 < _level->maxLevel()) {
837 837
            _level->liftHighestActive(new_level + 1);
838 838
          } else {
839 839
            // Calculation error
840 840
            _level->liftHighestActiveToTop();
841 841
          }
842 842
          if (_level->emptyLevel(level)) {
843 843
            // Calculation error
844 844
            _level->liftToTop(level);
845 845
          }
846 846
        } else {
847 847
          _level->deactivate(n);
848 848
        }
849 849

	
850 850
      }
851 851
    }
852 852

	
853 853
    /// \brief Runs the preflow algorithm.
854 854
    ///
855 855
    /// Runs the preflow algorithm.
856 856
    /// \note pf.run() is just a shortcut of the following code.
857 857
    /// \code
858 858
    ///   pf.init();
859 859
    ///   pf.startFirstPhase();
860 860
    ///   pf.startSecondPhase();
861 861
    /// \endcode
862 862
    void run() {
863 863
      init();
864 864
      startFirstPhase();
865 865
      startSecondPhase();
866 866
    }
867 867

	
868 868
    /// \brief Runs the preflow algorithm to compute the minimum cut.
869 869
    ///
870 870
    /// Runs the preflow algorithm to compute the minimum cut.
871 871
    /// \note pf.runMinCut() is just a shortcut of the following code.
872 872
    /// \code
873 873
    ///   pf.init();
874 874
    ///   pf.startFirstPhase();
875 875
    /// \endcode
876 876
    void runMinCut() {
877 877
      init();
878 878
      startFirstPhase();
879 879
    }
880 880

	
881 881
    /// @}
882 882

	
883 883
    /// \name Query Functions
884 884
    /// The results of the preflow algorithm can be obtained using these
885 885
    /// functions.\n
886 886
    /// Either one of the \ref run() "run*()" functions or one of the
887 887
    /// \ref startFirstPhase() "start*()" functions should be called
888 888
    /// before using them.
889 889

	
890 890
    ///@{
891 891

	
892 892
    /// \brief Returns the value of the maximum flow.
893 893
    ///
894 894
    /// Returns the value of the maximum flow by returning the excess
895 895
    /// of the target node. This value equals to the value of
896 896
    /// the maximum flow already after the first phase of the algorithm.
897 897
    ///
898 898
    /// \pre Either \ref run() or \ref init() must be called before
899 899
    /// using this function.
900
    Flow flowValue() const {
900
    Value flowValue() const {
901 901
      return (*_excess)[_target];
902 902
    }
903 903

	
904
    /// \brief Returns the flow on the given arc.
904
    /// \brief Returns the flow value on the given arc.
905 905
    ///
906
    /// Returns the flow on the given arc. This method can
906
    /// Returns the flow value on the given arc. This method can
907 907
    /// be called after the second phase of the algorithm.
908 908
    ///
909 909
    /// \pre Either \ref run() or \ref init() must be called before
910 910
    /// using this function.
911
    Flow flow(const Arc& arc) const {
911
    Value flow(const Arc& arc) const {
912 912
      return (*_flow)[arc];
913 913
    }
914 914

	
915 915
    /// \brief Returns a const reference to the flow map.
916 916
    ///
917 917
    /// Returns a const reference to the arc map storing the found flow.
918 918
    /// This method can be called after the second phase of the algorithm.
919 919
    ///
920 920
    /// \pre Either \ref run() or \ref init() must be called before
921 921
    /// using this function.
922 922
    const FlowMap& flowMap() const {
923 923
      return *_flow;
924 924
    }
925 925

	
926 926
    /// \brief Returns \c true when the node is on the source side of the
927 927
    /// minimum cut.
928 928
    ///
929 929
    /// Returns true when the node is on the source side of the found
930 930
    /// minimum cut. This method can be called both after running \ref
931 931
    /// startFirstPhase() and \ref startSecondPhase().
932 932
    ///
933 933
    /// \pre Either \ref run() or \ref init() must be called before
934 934
    /// using this function.
935 935
    bool minCut(const Node& node) const {
936 936
      return ((*_level)[node] == _level->maxLevel()) == _phase;
937 937
    }
938 938

	
939 939
    /// \brief Gives back a minimum value cut.
940 940
    ///
941 941
    /// Sets \c cutMap to the characteristic vector of a minimum value
942 942
    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
943 943
    /// node map with \c bool (or convertible) value type.
944 944
    ///
945 945
    /// This method can be called both after running \ref startFirstPhase()
946 946
    /// and \ref startSecondPhase(). The result after the second phase
947 947
    /// could be slightly different if inexact computation is used.
948 948
    ///
949 949
    /// \note This function calls \ref minCut() for each node, so it runs in
950 950
    /// O(n) time.
951 951
    ///
952 952
    /// \pre Either \ref run() or \ref init() must be called before
953 953
    /// using this function.
954 954
    template <typename CutMap>
955 955
    void minCutMap(CutMap& cutMap) const {
956 956
      for (NodeIt n(_graph); n != INVALID; ++n) {
957 957
        cutMap.set(n, minCut(n));
958 958
      }
959 959
    }
960 960

	
961 961
    /// @}
962 962
  };
963 963
}
964 964

	
965 965
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#include <sstream>
20 20
#include <lemon/lp_skeleton.h>
21 21
#include "test_tools.h"
22 22
#include <lemon/tolerance.h>
23 23

	
24
#ifdef HAVE_CONFIG_H
25 24
#include <lemon/config.h>
26
#endif
27 25

	
28 26
#ifdef LEMON_HAVE_GLPK
29 27
#include <lemon/glpk.h>
30 28
#endif
31 29

	
32 30
#ifdef LEMON_HAVE_CPLEX
33 31
#include <lemon/cplex.h>
34 32
#endif
35 33

	
36 34
#ifdef LEMON_HAVE_SOPLEX
37 35
#include <lemon/soplex.h>
38 36
#endif
39 37

	
40 38
#ifdef LEMON_HAVE_CLP
41 39
#include <lemon/clp.h>
42 40
#endif
43 41

	
44 42
using namespace lemon;
45 43

	
46 44
void lpTest(LpSolver& lp)
47 45
{
48 46

	
49 47
  typedef LpSolver LP;
50 48

	
51 49
  std::vector<LP::Col> x(10);
52 50
  //  for(int i=0;i<10;i++) x.push_back(lp.addCol());
53 51
  lp.addColSet(x);
54 52
  lp.colLowerBound(x,1);
55 53
  lp.colUpperBound(x,1);
56 54
  lp.colBounds(x,1,2);
57 55

	
58 56
  std::vector<LP::Col> y(10);
59 57
  lp.addColSet(y);
60 58

	
61 59
  lp.colLowerBound(y,1);
62 60
  lp.colUpperBound(y,1);
63 61
  lp.colBounds(y,1,2);
64 62

	
65 63
  std::map<int,LP::Col> z;
66 64

	
67 65
  z.insert(std::make_pair(12,INVALID));
68 66
  z.insert(std::make_pair(2,INVALID));
69 67
  z.insert(std::make_pair(7,INVALID));
70 68
  z.insert(std::make_pair(5,INVALID));
71 69

	
72 70
  lp.addColSet(z);
73 71

	
74 72
  lp.colLowerBound(z,1);
75 73
  lp.colUpperBound(z,1);
76 74
  lp.colBounds(z,1,2);
77 75

	
78 76
  {
79 77
    LP::Expr e,f,g;
80 78
    LP::Col p1,p2,p3,p4,p5;
81 79
    LP::Constr c;
82 80

	
83 81
    p1=lp.addCol();
84 82
    p2=lp.addCol();
85 83
    p3=lp.addCol();
86 84
    p4=lp.addCol();
87 85
    p5=lp.addCol();
88 86

	
89 87
    e[p1]=2;
90 88
    *e=12;
91 89
    e[p1]+=2;
92 90
    *e+=12;
93 91
    e[p1]-=2;
94 92
    *e-=12;
95 93

	
96 94
    e=2;
97 95
    e=2.2;
98 96
    e=p1;
99 97
    e=f;
100 98

	
101 99
    e+=2;
102 100
    e+=2.2;
103 101
    e+=p1;
104 102
    e+=f;
105 103

	
106 104
    e-=2;
107 105
    e-=2.2;
108 106
    e-=p1;
109 107
    e-=f;
110 108

	
111 109
    e*=2;
112 110
    e*=2.2;
113 111
    e/=2;
114 112
    e/=2.2;
115 113

	
116 114
    e=((p1+p2)+(p1-p2)+(p1+12)+(12+p1)+(p1-12)+(12-p1)+
117 115
       (f+12)+(12+f)+(p1+f)+(f+p1)+(f+g)+
118 116
       (f-12)+(12-f)+(p1-f)+(f-p1)+(f-g)+
119 117
       2.2*f+f*2.2+f/2.2+
120 118
       2*f+f*2+f/2+
121 119
       2.2*p1+p1*2.2+p1/2.2+
122 120
       2*p1+p1*2+p1/2
123 121
       );
124 122

	
125 123

	
126 124
    c = (e  <= f  );
127 125
    c = (e  <= 2.2);
128 126
    c = (e  <= 2  );
129 127
    c = (e  <= p1 );
130 128
    c = (2.2<= f  );
131 129
    c = (2  <= f  );
132 130
    c = (p1 <= f  );
133 131
    c = (p1 <= p2 );
134 132
    c = (p1 <= 2.2);
135 133
    c = (p1 <= 2  );
136 134
    c = (2.2<= p2 );
137 135
    c = (2  <= p2 );
138 136

	
139 137
    c = (e  >= f  );
140 138
    c = (e  >= 2.2);
141 139
    c = (e  >= 2  );
142 140
    c = (e  >= p1 );
143 141
    c = (2.2>= f  );
144 142
    c = (2  >= f  );
145 143
    c = (p1 >= f  );
146 144
    c = (p1 >= p2 );
147 145
    c = (p1 >= 2.2);
148 146
    c = (p1 >= 2  );
149 147
    c = (2.2>= p2 );
150 148
    c = (2  >= p2 );
151 149

	
152 150
    c = (e  == f  );
153 151
    c = (e  == 2.2);
154 152
    c = (e  == 2  );
155 153
    c = (e  == p1 );
156 154
    c = (2.2== f  );
157 155
    c = (2  == f  );
158 156
    c = (p1 == f  );
159 157
    //c = (p1 == p2 );
160 158
    c = (p1 == 2.2);
161 159
    c = (p1 == 2  );
162 160
    c = (2.2== p2 );
163 161
    c = (2  == p2 );
164 162

	
165 163
    c = ((2 <= e) <= 3);
166 164
    c = ((2 <= p1) <= 3);
167 165

	
168 166
    c = ((2 >= e) >= 3);
169 167
    c = ((2 >= p1) >= 3);
170 168

	
171 169
    e[x[3]]=2;
172 170
    e[x[3]]=4;
173 171
    e[x[3]]=1;
174 172
    *e=12;
175 173

	
176 174
    lp.addRow(-LP::INF,e,23);
177 175
    lp.addRow(-LP::INF,3.0*(x[1]+x[2]/2)-x[3],23);
178 176
    lp.addRow(-LP::INF,3.0*(x[1]+x[2]*2-5*x[3]+12-x[4]/3)+2*x[4]-4,23);
179 177

	
180 178
    lp.addRow(x[1]+x[3]<=x[5]-3);
181 179
    lp.addRow((-7<=x[1]+x[3]-12)<=3);
182 180
    lp.addRow(x[1]<=x[5]);
183 181

	
184 182
    std::ostringstream buf;
185 183

	
186 184

	
187 185
    e=((p1+p2)+(p1-0.99*p2));
188 186
    //e.prettyPrint(std::cout);
189 187
    //(e<=2).prettyPrint(std::cout);
190 188
    double tolerance=0.001;
191 189
    e.simplify(tolerance);
192 190
    buf << "Coeff. of p2 should be 0.01";
193 191
    check(e[p2]>0, buf.str());
194 192

	
195 193
    tolerance=0.02;
196 194
    e.simplify(tolerance);
197 195
    buf << "Coeff. of p2 should be 0";
198 196
    check(const_cast<const LpSolver::Expr&>(e)[p2]==0, buf.str());
199 197

	
200 198
    //Test for clone/new
201 199
    LP* lpnew = lp.newSolver();
202 200
    LP* lpclone = lp.cloneSolver();
203 201
    delete lpnew;
204 202
    delete lpclone;
205 203

	
206 204
  }
207 205

	
208 206
  {
209 207
    LP::DualExpr e,f,g;
210 208
    LP::Row p1 = INVALID, p2 = INVALID, p3 = INVALID,
211 209
      p4 = INVALID, p5 = INVALID;
212 210

	
213 211
    e[p1]=2;
214 212
    e[p1]+=2;
215 213
    e[p1]-=2;
216 214

	
217 215
    e=p1;
218 216
    e=f;
219 217

	
220 218
    e+=p1;
221 219
    e+=f;
222 220

	
223 221
    e-=p1;
224 222
    e-=f;
225 223

	
226 224
    e*=2;
227 225
    e*=2.2;
228 226
    e/=2;
229 227
    e/=2.2;
230 228

	
231 229
    e=((p1+p2)+(p1-p2)+
232 230
       (p1+f)+(f+p1)+(f+g)+
233 231
       (p1-f)+(f-p1)+(f-g)+
234 232
       2.2*f+f*2.2+f/2.2+
235 233
       2*f+f*2+f/2+
236 234
       2.2*p1+p1*2.2+p1/2.2+
237 235
       2*p1+p1*2+p1/2
238 236
       );
239 237
  }
240 238

	
241 239
}
242 240

	
243 241
void solveAndCheck(LpSolver& lp, LpSolver::ProblemType stat,
244 242
                   double exp_opt) {
245 243
  using std::string;
246 244
  lp.solve();
247 245

	
248 246
  std::ostringstream buf;
249 247
  buf << "PrimalType should be: " << int(stat) << int(lp.primalType());
250 248

	
251 249
  check(lp.primalType()==stat, buf.str());
252 250

	
253 251
  if (stat ==  LpSolver::OPTIMAL) {
254 252
    std::ostringstream sbuf;
255 253
    sbuf << "Wrong optimal value (" << lp.primal() <<") with "
256 254
         << lp.solverName() <<"\n     the right optimum is " << exp_opt;
257 255
    check(std::abs(lp.primal()-exp_opt) < 1e-3, sbuf.str());
258 256
  }
259 257
}
260 258

	
261 259
void aTest(LpSolver & lp)
262 260
{
263 261
  typedef LpSolver LP;
264 262

	
265 263
 //The following example is very simple
266 264

	
267 265
  typedef LpSolver::Row Row;
268 266
  typedef LpSolver::Col Col;
269 267

	
270 268

	
271 269
  Col x1 = lp.addCol();
272 270
  Col x2 = lp.addCol();
273 271

	
274 272

	
275 273
  //Constraints
276 274
  Row upright=lp.addRow(x1+2*x2 <=1);
277 275
  lp.addRow(x1+x2 >=-1);
278 276
  lp.addRow(x1-x2 <=1);
279 277
  lp.addRow(x1-x2 >=-1);
280 278
  //Nonnegativity of the variables
281 279
  lp.colLowerBound(x1, 0);
282 280
  lp.colLowerBound(x2, 0);
283 281
  //Objective function
284 282
  lp.obj(x1+x2);
285 283

	
286 284
  lp.sense(lp.MAX);
287 285

	
288 286
  //Testing the problem retrieving routines
289 287
  check(lp.objCoeff(x1)==1,"First term should be 1 in the obj function!");
290 288
  check(lp.sense() == lp.MAX,"This is a maximization!");
291 289
  check(lp.coeff(upright,x1)==1,"The coefficient in question is 1!");
292 290
  check(lp.colLowerBound(x1)==0,
293 291
        "The lower bound for variable x1 should be 0.");
294 292
  check(lp.colUpperBound(x1)==LpSolver::INF,
295 293
        "The upper bound for variable x1 should be infty.");
296 294
  check(lp.rowLowerBound(upright) == -LpSolver::INF,
297 295
        "The lower bound for the first row should be -infty.");
298 296
  check(lp.rowUpperBound(upright)==1,
299 297
        "The upper bound for the first row should be 1.");
300 298
  LpSolver::Expr e = lp.row(upright);
301 299
  check(e[x1] == 1, "The first coefficient should 1.");
302 300
  check(e[x2] == 2, "The second coefficient should 1.");
303 301

	
304 302
  lp.row(upright, x1+x2 <=1);
305 303
  e = lp.row(upright);
306 304
  check(e[x1] == 1, "The first coefficient should 1.");
307 305
  check(e[x2] == 1, "The second coefficient should 1.");
308 306

	
309 307
  LpSolver::DualExpr de = lp.col(x1);
310 308
  check(  de[upright] == 1, "The first coefficient should 1.");
311 309

	
312 310
  LpSolver* clp = lp.cloneSolver();
313 311

	
314 312
  //Testing the problem retrieving routines
315 313
  check(clp->objCoeff(x1)==1,"First term should be 1 in the obj function!");
316 314
  check(clp->sense() == clp->MAX,"This is a maximization!");
317 315
  check(clp->coeff(upright,x1)==1,"The coefficient in question is 1!");
318 316
  //  std::cout<<lp.colLowerBound(x1)<<std::endl;
319 317
  check(clp->colLowerBound(x1)==0,
320 318
        "The lower bound for variable x1 should be 0.");
321 319
  check(clp->colUpperBound(x1)==LpSolver::INF,
322 320
        "The upper bound for variable x1 should be infty.");
323 321

	
324 322
  check(lp.rowLowerBound(upright)==-LpSolver::INF,
325 323
        "The lower bound for the first row should be -infty.");
326 324
  check(lp.rowUpperBound(upright)==1,
327 325
        "The upper bound for the first row should be 1.");
328 326
  e = clp->row(upright);
329 327
  check(e[x1] == 1, "The first coefficient should 1.");
330 328
  check(e[x2] == 1, "The second coefficient should 1.");
331 329

	
332 330
  de = clp->col(x1);
333 331
  check(de[upright] == 1, "The first coefficient should 1.");
334 332

	
335 333
  delete clp;
336 334

	
337 335
  //Maximization of x1+x2
338 336
  //over the triangle with vertices (0,0) (0,1) (1,0)
339 337
  double expected_opt=1;
340 338
  solveAndCheck(lp, LpSolver::OPTIMAL, expected_opt);
341 339

	
342 340
  //Minimization
343 341
  lp.sense(lp.MIN);
344 342
  expected_opt=0;
345 343
  solveAndCheck(lp, LpSolver::OPTIMAL, expected_opt);
346 344

	
347 345
  //Vertex (-1,0) instead of (0,0)
348 346
  lp.colLowerBound(x1, -LpSolver::INF);
349 347
  expected_opt=-1;
350 348
  solveAndCheck(lp, LpSolver::OPTIMAL, expected_opt);
351 349

	
352 350
  //Erase one constraint and return to maximization
353 351
  lp.erase(upright);
354 352
  lp.sense(lp.MAX);
355 353
  expected_opt=LpSolver::INF;
356 354
  solveAndCheck(lp, LpSolver::UNBOUNDED, expected_opt);
357 355

	
358 356
  //Infeasibilty
359 357
  lp.addRow(x1+x2 <=-2);
360 358
  solveAndCheck(lp, LpSolver::INFEASIBLE, expected_opt);
361 359

	
362 360
}
363 361

	
364 362
template<class LP>
365 363
void cloneTest()
366 364
{
367 365
  //Test for clone/new
368 366

	
369 367
  LP* lp = new LP();
370 368
  LP* lpnew = lp->newSolver();
371 369
  LP* lpclone = lp->cloneSolver();
372 370
  delete lp;
373 371
  delete lpnew;
374 372
  delete lpclone;
375 373
}
376 374

	
377 375
int main()
378 376
{
379 377
  LpSkeleton lp_skel;
380 378
  lpTest(lp_skel);
381 379

	
382 380
#ifdef LEMON_HAVE_GLPK
383 381
  {
384 382
    GlpkLp lp_glpk1,lp_glpk2;
385 383
    lpTest(lp_glpk1);
386 384
    aTest(lp_glpk2);
387 385
    cloneTest<GlpkLp>();
388 386
  }
389 387
#endif
390 388

	
391 389
#ifdef LEMON_HAVE_CPLEX
392 390
  try {
393 391
    CplexLp lp_cplex1,lp_cplex2;
394 392
    lpTest(lp_cplex1);
395 393
    aTest(lp_cplex2);
396 394
    cloneTest<CplexLp>();
397 395
  } catch (CplexEnv::LicenseError& error) {
398 396
    check(false, error.what());
399 397
  }
400 398
#endif
401 399

	
402 400
#ifdef LEMON_HAVE_SOPLEX
403 401
  {
404 402
    SoplexLp lp_soplex1,lp_soplex2;
405 403
    lpTest(lp_soplex1);
406 404
    aTest(lp_soplex2);
407 405
    cloneTest<SoplexLp>();
408 406
  }
409 407
#endif
410 408

	
411 409
#ifdef LEMON_HAVE_CLP
412 410
  {
413 411
    ClpLp lp_clp1,lp_clp2;
414 412
    lpTest(lp_clp1);
415 413
    aTest(lp_clp2);
416 414
    cloneTest<ClpLp>();
417 415
  }
418 416
#endif
419 417

	
420 418
  return 0;
421 419
}

Changeset was too big and was cut off... Show full diff

0 comments (0 inline)