Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
line_graph.h
Go to the documentation of this file.
1// Copyright 2010-2025 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#ifndef OR_TOOLS_GRAPH_LINE_GRAPH_H_
15#define OR_TOOLS_GRAPH_LINE_GRAPH_H_
16
18
19namespace operations_research {
20
21// Builds a directed line graph for `graph` (see "directed line graph" in
22// http://en.wikipedia.org/wiki/Line_graph). Arcs of the original graph
23// become nodes and the new graph contains only nodes created from arcs in the
24// original graph (we use the notation (a->b) for these new nodes); the index
25// of the node (a->b) in the new graph is exactly the same as the index of the
26// arc a->b in the original graph.
27// An arc from node (a->b) to node (c->d) in the new graph is added if and only
28// if b == c in the original graph.
29// This method expects that `line_graph` is an empty graph (it has no nodes
30// and no arcs).
31// Returns false on an error.
32template <typename GraphType>
33bool BuildLineGraph(const GraphType& graph, GraphType* const line_graph) {
34 if (line_graph == nullptr) {
35 LOG(DFATAL) << "line_graph must not be NULL";
36 return false;
37 }
38 if (line_graph->num_nodes() != 0) {
39 LOG(DFATAL) << "line_graph must be empty";
40 return false;
41 }
42 // Sizing then filling.
43 using NodeIndex = typename GraphType::NodeIndex;
44 using ArcIndex = typename GraphType::ArcIndex;
45 ArcIndex num_arcs = 0;
46 for (const ArcIndex arc : graph.AllForwardArcs()) {
47 const NodeIndex head = graph.Head(arc);
48 num_arcs += graph.OutDegree(head);
49 }
50 line_graph->Reserve(graph.num_arcs(), num_arcs);
51 for (const ArcIndex arc : graph.AllForwardArcs()) {
52 const NodeIndex head = graph.Head(arc);
53 for (const ArcIndex outgoing_arc : graph.OutgoingArcs(head)) {
54 line_graph->AddArc(arc, outgoing_arc);
55 }
56 }
57 return true;
58}
59
60} // namespace operations_research
61
62#endif // OR_TOOLS_GRAPH_LINE_GRAPH_H_
In SWIG mode, we don't want anything besides these top-level includes.
bool BuildLineGraph(const GraphType &graph, GraphType *const line_graph)
Definition line_graph.h:33