Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
util.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14// A collections of utilities for the Graph classes in ./graph.h.
15
16#ifndef UTIL_GRAPH_UTIL_H_
17#define UTIL_GRAPH_UTIL_H_
18
19#include <algorithm>
20#include <cstdint>
21#include <map>
22#include <memory>
23#include <set>
24#include <string>
25#include <utility>
26#include <vector>
27
28#include "absl/container/btree_map.h"
29#include "absl/container/flat_hash_map.h"
30#include "absl/container/inlined_vector.h"
31#include "absl/types/span.h"
32#include "ortools/base/hash.h"
35#include "ortools/graph/graph.h"
37
38namespace util {
39
40// Here's a set of simple diagnosis tools. Notes:
41// - A self-arc is an arc from a node to itself.
42// - We say that an arc A->B is duplicate when there is another arc A->B in the
43// same graph.
44// - A graph is said "weakly connected" if it is connected when considering all
45// arcs as undirected edges.
46// - A graph is said "symmetric" iff for all (a, b), the number of arcs a->b
47// is equal to the number of arcs b->a.
48//
49// All these diagnosis work in O(graph size), since the inverse Ackerman
50// function is <= 5 for all practical instances, and are very fast.
51//
52// If the graph is a "static" kind, they must be finalized, except for
53// GraphHasSelfArcs() and GraphIsWeaklyConnected() which also support
54// non-finalized StaticGraph<>.
55template <class Graph>
56bool GraphHasSelfArcs(const Graph& graph);
57template <class Graph>
58bool GraphHasDuplicateArcs(const Graph& graph);
59template <class Graph>
60bool GraphIsSymmetric(const Graph& graph);
61template <class Graph>
62bool GraphIsWeaklyConnected(const Graph& graph);
63
64// Returns a fresh copy of a given graph.
65template <class Graph>
66std::unique_ptr<Graph> CopyGraph(const Graph& graph);
67
68// Creates a remapped copy of graph "graph", where node i becomes node
69// new_node_index[i].
70// "new_node_index" must be a valid permutation of [0..num_nodes-1] or the
71// behavior is undefined (it may die).
72// Note that you can call IsValidPermutation() to check it yourself.
73template <class Graph>
74std::unique_ptr<Graph> RemapGraph(const Graph& graph,
75 absl::Span<const int> new_node_index);
76
77// Gets the induced subgraph of "graph" restricted to the nodes in "nodes":
78// the resulting graph will have exactly nodes.size() nodes, and its
79// node #0 will be the former graph's node #nodes[0], etc.
80// See https://en.wikipedia.org/wiki/Induced_subgraph .
81// The "nodes" must be a valid subset (no repetitions) of
82// [0..graph.num_nodes()-1], or the behavior is undefined (it may die).
83// Note that you can call IsSubsetOf0N() to check it yourself.
84//
85// Current complexity: O(num old nodes + num new arcs). It could easily
86// be done in O(num new nodes + num new arcs) but with a higher constant.
87template <class Graph>
88std::unique_ptr<Graph> GetSubgraphOfNodes(const Graph& graph,
89 absl::Span<const int> nodes);
90
91// This can be used to view a directed graph (that supports reverse arcs)
92// from graph.h as un undirected graph: operator[](node) returns a
93// pseudo-container that iterates over all nodes adjacent to "node" (from
94// outgoing or incoming arcs).
95// CAVEAT: Self-arcs (aka loops) will appear twice.
96//
97// Example:
98// ReverseArcsStaticGraph<> dgraph;
99// ...
100// UndirectedAdjacencyListsOfDirectedGraph<decltype(dgraph)> ugraph(dgraph);
101// for (int neighbor_of_node_42 : ugraph[42]) { ... }
102template <class Graph>
104 public:
106 : graph_(graph) {}
107
108 typedef typename Graph::OutgoingOrOppositeIncomingArcIterator ArcIterator;
110 public:
111 explicit AdjacencyListIterator(const Graph& graph, ArcIterator&& arc_it)
112 : ArcIterator(arc_it), graph_(graph) {}
113 // Overwrite operator* to return the heads of the arcs.
114 typename Graph::NodeIndex operator*() const {
115 return graph_.Head(ArcIterator::operator*());
116 }
117
118 private:
119 const Graph& graph_;
120 };
121
122 // Returns a pseudo-container of all the nodes adjacent to "node".
124 const auto& arc_range = graph_.OutgoingOrOppositeIncomingArcs(node);
125 return {AdjacencyListIterator(graph_, arc_range.begin()),
126 AdjacencyListIterator(graph_, arc_range.end())};
127 }
128
129 private:
130 const Graph& graph_;
131};
132
133// Computes the weakly connected components of a directed graph that
134// provides the OutgoingOrOppositeIncomingArcs() API, and returns them
135// as a mapping from node to component index. See GetConnectedComponents().
136template <class Graph>
141
142// Returns true iff the given vector is a subset of [0..n-1], i.e.
143// all elements i are such that 0 <= i < n and no two elements are equal.
144// "n" must be >= 0 or the result is undefined.
145bool IsSubsetOf0N(absl::Span<const int> v, int n);
146
147// Returns true iff the given vector is a permutation of [0..size()-1].
148inline bool IsValidPermutation(absl::Span<const int> v) {
149 return IsSubsetOf0N(v, v.size());
150}
151
152// Returns a copy of "graph", without self-arcs and duplicate arcs.
153template <class Graph>
154std::unique_ptr<Graph> RemoveSelfArcsAndDuplicateArcs(const Graph& graph);
155
156// Given an arc path, changes it to a sub-path with the same source and
157// destination but without any cycle. Nothing happen if the path was already
158// without cycle.
159//
160// The graph class should support Tail(arc) and Head(arc). They should both
161// return an integer representing the corresponding tail/head of the passed arc.
162//
163// TODO(user): In some cases, there is more than one possible solution. We could
164// take some arc costs and return the cheapest path instead. Or return the
165// shortest path in term of number of arcs.
166template <class Graph>
167void RemoveCyclesFromPath(const Graph& graph, std::vector<int>* arc_path);
168
169// Returns true iff the given path contains a cycle.
170template <class Graph>
171bool PathHasCycle(const Graph& graph, absl::Span<const int> arc_path);
172
173// Returns a vector representing a mapping from arcs to arcs such that each arc
174// is mapped to another arc with its (tail, head) flipped, if such an arc
175// exists (otherwise it is mapped to -1).
176// If the graph is symmetric, the returned mapping is bijective and reflexive,
177// i.e. out[out[arc]] = arc for all "arc", where "out" is the returned vector.
178// If "die_if_not_symmetric" is true, this function CHECKs() that the graph
179// is symmetric.
180//
181// Self-arcs are always mapped to themselves.
182//
183// Note that since graphs may have multi-arcs, the mapping isn't necessarily
184// unique, hence the function name.
185//
186// PERFORMANCE: If you see this function taking too much memory and/or too much
187// time, reach out to viger@: one could halve the memory usage and speed it up.
188template <class Graph>
189std::vector<int> ComputeOnePossibleReverseArcMapping(const Graph& graph,
190 bool die_if_not_symmetric);
191
192// Implementations of the templated methods.
193
194template <class Graph>
195bool GraphHasSelfArcs(const Graph& graph) {
196 for (const auto arc : graph.AllForwardArcs()) {
197 if (graph.Tail(arc) == graph.Head(arc)) return true;
198 }
199 return false;
200}
201
202template <class Graph>
203bool GraphHasDuplicateArcs(const Graph& graph) {
204 typedef typename Graph::ArcIndex ArcIndex;
205 typedef typename Graph::NodeIndex NodeIndex;
206 std::vector<bool> tmp_node_mask(graph.num_nodes(), false);
207 for (const NodeIndex tail : graph.AllNodes()) {
208 for (const ArcIndex arc : graph.OutgoingArcs(tail)) {
209 const NodeIndex head = graph.Head(arc);
210 if (tmp_node_mask[head]) return true;
211 tmp_node_mask[head] = true;
212 }
213 for (const ArcIndex arc : graph.OutgoingArcs(tail)) {
214 tmp_node_mask[graph.Head(arc)] = false;
215 }
216 }
217 return false;
218}
219
220template <class Graph>
221bool GraphIsSymmetric(const Graph& graph) {
222 typedef typename Graph::NodeIndex NodeIndex;
223 typedef typename Graph::ArcIndex ArcIndex;
224 // Create a reverse copy of the graph.
225 StaticGraph<NodeIndex, ArcIndex> reverse_graph(graph.num_nodes(),
226 graph.num_arcs());
227 for (const NodeIndex node : graph.AllNodes()) {
228 for (const ArcIndex arc : graph.OutgoingArcs(node)) {
229 reverse_graph.AddArc(graph.Head(arc), node);
230 }
231 }
232 reverse_graph.Build();
233 // Compare the graph to its reverse, one adjacency list at a time.
234 std::vector<ArcIndex> count(graph.num_nodes(), 0);
235 for (const NodeIndex node : graph.AllNodes()) {
236 for (const ArcIndex arc : graph.OutgoingArcs(node)) {
237 ++count[graph.Head(arc)];
238 }
239 for (const ArcIndex arc : reverse_graph.OutgoingArcs(node)) {
240 if (--count[reverse_graph.Head(arc)] < 0) return false;
241 }
242 for (const ArcIndex arc : graph.OutgoingArcs(node)) {
243 if (count[graph.Head(arc)] != 0) return false;
244 }
245 }
246 return true;
247}
248
249template <class Graph>
250bool GraphIsWeaklyConnected(const Graph& graph) {
251 typedef typename Graph::NodeIndex NodeIndex;
252 static_assert(std::numeric_limits<NodeIndex>::max() <= INT_MAX,
253 "GraphIsWeaklyConnected() isn't yet implemented for graphs"
254 " that support more than INT_MAX nodes. Reach out to"
255 " or-core-team@ if you need this.");
256 if (graph.num_nodes() == 0) return true;
258 union_find.SetNumberOfNodes(graph.num_nodes());
259 for (typename Graph::ArcIndex arc = 0; arc < graph.num_arcs(); ++arc) {
260 union_find.AddEdge(graph.Tail(arc), graph.Head(arc));
261 }
262 return union_find.GetNumberOfComponents() == 1;
263}
264
265template <class Graph>
266std::unique_ptr<Graph> CopyGraph(const Graph& graph) {
267 std::unique_ptr<Graph> new_graph(
268 new Graph(graph.num_nodes(), graph.num_arcs()));
269 for (const auto node : graph.AllNodes()) {
270 for (const auto arc : graph.OutgoingArcs(node)) {
271 new_graph->AddArc(node, graph.Head(arc));
272 }
273 }
274 new_graph->Build();
275 return new_graph;
276}
277
278template <class Graph>
279std::unique_ptr<Graph> RemapGraph(const Graph& old_graph,
280 absl::Span<const int> new_node_index) {
281 DCHECK(IsValidPermutation(new_node_index)) << "Invalid permutation";
282 const int num_nodes = old_graph.num_nodes();
283 CHECK_EQ(new_node_index.size(), num_nodes);
284 std::unique_ptr<Graph> new_graph(new Graph(num_nodes, old_graph.num_arcs()));
285 typedef typename Graph::NodeIndex NodeIndex;
286 typedef typename Graph::ArcIndex ArcIndex;
287 for (const NodeIndex node : old_graph.AllNodes()) {
288 for (const ArcIndex arc : old_graph.OutgoingArcs(node)) {
289 new_graph->AddArc(new_node_index[node],
290 new_node_index[old_graph.Head(arc)]);
291 }
292 }
293 new_graph->Build();
294 return new_graph;
295}
296
297template <class Graph>
298std::unique_ptr<Graph> GetSubgraphOfNodes(const Graph& old_graph,
299 absl::Span<const int> nodes) {
300 typedef typename Graph::NodeIndex NodeIndex;
301 typedef typename Graph::ArcIndex ArcIndex;
302 DCHECK(IsSubsetOf0N(nodes, old_graph.num_nodes())) << "Invalid subset";
303 std::vector<NodeIndex> new_node_index(old_graph.num_nodes(), -1);
304 for (NodeIndex new_index = 0; new_index < nodes.size(); ++new_index) {
305 new_node_index[nodes[new_index]] = new_index;
306 }
307 // Do a first pass to count the arcs, so that we don't allocate more memory
308 // than needed.
309 ArcIndex num_arcs = 0;
310 for (const NodeIndex node : nodes) {
311 for (const ArcIndex arc : old_graph.OutgoingArcs(node)) {
312 if (new_node_index[old_graph.Head(arc)] != -1) ++num_arcs;
313 }
314 }
315 // A second pass where we actually copy the subgraph.
316 // NOTE(user): there might seem to be a bit of duplication with RemapGraph(),
317 // but there is a key difference: the loop below only iterates on "nodes",
318 // which could be much smaller than all the graph's nodes.
319 std::unique_ptr<Graph> new_graph(new Graph(nodes.size(), num_arcs));
320 for (NodeIndex new_tail = 0; new_tail < nodes.size(); ++new_tail) {
321 const NodeIndex old_tail = nodes[new_tail];
322 for (const ArcIndex arc : old_graph.OutgoingArcs(old_tail)) {
323 const NodeIndex new_head = new_node_index[old_graph.Head(arc)];
324 if (new_head != -1) new_graph->AddArc(new_tail, new_head);
325 }
326 }
327 new_graph->Build();
328 return new_graph;
329}
330
331template <class Graph>
332std::unique_ptr<Graph> RemoveSelfArcsAndDuplicateArcs(const Graph& graph) {
333 std::unique_ptr<Graph> g(new Graph(graph.num_nodes(), graph.num_arcs()));
334 typedef typename Graph::ArcIndex ArcIndex;
335 typedef typename Graph::NodeIndex NodeIndex;
336 std::vector<bool> tmp_node_mask(graph.num_nodes(), false);
337 for (const NodeIndex tail : graph.AllNodes()) {
338 for (const ArcIndex arc : graph.OutgoingArcs(tail)) {
339 const NodeIndex head = graph.Head(arc);
340 if (head != tail && !tmp_node_mask[head]) {
341 tmp_node_mask[head] = true;
342 g->AddArc(tail, head);
343 }
344 }
345 for (const ArcIndex arc : graph.OutgoingArcs(tail)) {
346 tmp_node_mask[graph.Head(arc)] = false;
347 }
348 }
349 g->Build();
350 return g;
351}
352
353template <class Graph>
354void RemoveCyclesFromPath(const Graph& graph, std::vector<int>* arc_path) {
355 if (arc_path->empty()) return;
356
357 // This maps each node to the latest arc in the given path that leaves it.
358 absl::btree_map<int, int> last_arc_leaving_node;
359 for (const int arc : *arc_path) last_arc_leaving_node[graph.Tail(arc)] = arc;
360
361 // Special case for the destination.
362 // Note that this requires that -1 is not a valid arc of Graph.
363 last_arc_leaving_node[graph.Head(arc_path->back())] = -1;
364
365 // Reconstruct the path by starting at the source and then following the
366 // "next" arcs. We override the given arc_path at the same time.
367 int node = graph.Tail(arc_path->front());
368 int new_size = 0;
369 while (new_size < arc_path->size()) { // To prevent cycle on bad input.
370 const int arc = gtl::FindOrDie(last_arc_leaving_node, node);
371 if (arc == -1) break;
372 (*arc_path)[new_size++] = arc;
373 node = graph.Head(arc);
374 }
375 arc_path->resize(new_size);
376}
377
378template <class Graph>
379bool PathHasCycle(const Graph& graph, absl::Span<const int> arc_path) {
380 if (arc_path.empty()) return false;
381 std::set<int> seen;
382 seen.insert(graph.Tail(arc_path.front()));
383 for (const int arc : arc_path) {
384 if (!gtl::InsertIfNotPresent(&seen, graph.Head(arc))) return true;
385 }
386 return false;
387}
388
389template <class Graph>
391 const Graph& graph, bool die_if_not_symmetric) {
392 std::vector<int> reverse_arc(graph.num_arcs(), -1);
393 // We need a multi-map since a given (tail,head) may appear several times.
394 // NOTE(user): It's free, in terms of space, to use InlinedVector<int, 4>
395 // rather than std::vector<int>.
396 absl::flat_hash_map<std::pair</*tail*/ int, /*head*/ int>,
397 absl::InlinedVector<int, 4>>
398 arc_map;
399
400 for (int arc = 0; arc < graph.num_arcs(); ++arc) {
401 const int tail = graph.Tail(arc);
402 const int head = graph.Head(arc);
403 if (tail == head) {
404 // Special case: directly map any self-arc to itself.
405 reverse_arc[arc] = arc;
406 continue;
407 }
408 // Lookup for the reverse arc of the current one...
409 auto it = arc_map.find({head, tail});
410 if (it != arc_map.end()) {
411 // Found a reverse arc! Store the mapping and remove the
412 // reverse arc from the map.
413 reverse_arc[arc] = it->second.back();
414 reverse_arc[it->second.back()] = arc;
415 if (it->second.size() > 1) {
416 it->second.pop_back();
417 } else {
418 arc_map.erase(it);
419 }
420 } else {
421 // Reverse arc not in the map. Add the current arc to the map.
422 arc_map[{tail, head}].push_back(arc);
423 }
424 }
425 // Algorithm check, for debugging.
426 if (DEBUG_MODE) {
427 int64_t num_unmapped_arcs = 0;
428 for (const auto& p : arc_map) {
429 num_unmapped_arcs += p.second.size();
430 }
431 DCHECK_EQ(std::count(reverse_arc.begin(), reverse_arc.end(), -1),
432 num_unmapped_arcs);
433 }
434 if (die_if_not_symmetric) {
435 CHECK_EQ(arc_map.size(), 0)
436 << "The graph is not symmetric: " << arc_map.size() << " of "
437 << graph.num_arcs() << " arcs did not have a reverse.";
438 }
439 return reverse_arc;
440}
441
442} // namespace util
443
444#endif // UTIL_GRAPH_UTIL_H_
IntegerValue size
A connected components finder that only works on dense ints.
bool AddEdge(int node1, int node2)
NodeIndexType num_nodes() const
Definition graph.h:211
IntegerRange< NodeIndex > AllNodes() const
BaseGraph implementation -------------------------------------------------—.
Definition graph.h:969
ArcIndexType num_arcs() const
Returns the number of valid arcs in the graph.
Definition graph.h:215
BeginEndWrapper< OutgoingArcIterator > OutgoingArcs(NodeIndexType node) const
NodeIndexType Head(ArcIndexType arc) const
Definition graph.h:1153
ArcIndexType AddArc(NodeIndexType tail, NodeIndexType head)
Definition graph.h:1332
BeginEndWrapper< OutgoingArcIterator > OutgoingArcs(NodeIndexType node) const
NodeIndexType Head(ArcIndexType arc) const
Definition graph.h:1360
AdjacencyListIterator(const Graph &graph, ArcIterator &&arc_it)
Definition util.h:111
Graph::NodeIndex operator*() const
Overwrite operator* to return the heads of the arcs.
Definition util.h:114
UndirectedAdjacencyListsOfDirectedGraph(const Graph &graph)
Definition util.h:105
Graph::OutgoingOrOppositeIncomingArcIterator ArcIterator
Definition util.h:108
BeginEndWrapper< AdjacencyListIterator > operator[](int node) const
Returns a pseudo-container of all the nodes adjacent to "node".
Definition util.h:123
GraphType graph
int arc
const bool DEBUG_MODE
Definition macros.h:24
bool InsertIfNotPresent(Collection *const collection, const typename Collection::value_type &value)
Definition map_util.h:127
const Collection::value_type::second_type & FindOrDie(const Collection &collection, const typename Collection::value_type::first_type &key)
Definition map_util.h:211
A collections of i/o utilities for the Graph classes in ./graph.h.
void RemoveCyclesFromPath(const Graph &graph, std::vector< int > *arc_path)
Definition util.h:354
bool IsValidPermutation(absl::Span< const int > v)
Returns true iff the given vector is a permutation of [0..size()-1].
Definition util.h:148
std::unique_ptr< Graph > CopyGraph(const Graph &graph)
Returns a fresh copy of a given graph.
Definition util.h:266
std::vector< int > GetConnectedComponents(int num_nodes, const UndirectedGraph &graph)
bool PathHasCycle(const Graph &graph, absl::Span< const int > arc_path)
Returns true iff the given path contains a cycle.
Definition util.h:379
bool GraphHasDuplicateArcs(const Graph &graph)
Definition util.h:203
bool GraphIsSymmetric(const Graph &graph)
Definition util.h:221
std::unique_ptr< Graph > RemapGraph(const Graph &graph, absl::Span< const int > new_node_index)
Definition util.h:279
std::unique_ptr< Graph > RemoveSelfArcsAndDuplicateArcs(const Graph &graph)
Returns a copy of "graph", without self-arcs and duplicate arcs.
Definition util.h:332
std::vector< int > GetWeaklyConnectedComponents(const Graph &graph)
Definition util.h:137
bool GraphIsWeaklyConnected(const Graph &graph)
Definition util.h:250
bool GraphHasSelfArcs(const Graph &graph)
Implementations of the templated methods.
Definition util.h:195
bool IsSubsetOf0N(absl::Span< const int > v, int n)
Definition util.cc:22
std::unique_ptr< Graph > GetSubgraphOfNodes(const Graph &graph, absl::Span< const int > nodes)
Definition util.h:298
std::vector< int > ComputeOnePossibleReverseArcMapping(const Graph &graph, bool die_if_not_symmetric)
Definition util.h:390
ListGraph Graph
Defining the simplest Graph interface as Graph for convenience.
Definition graph.h:2407
int head
int tail
int nodes