Open
Graph Drawing
Framework

 v. snapshot-2017-02-16
 

SteinerTreePreprocessing.h
Go to the documentation of this file.
1 
32 #pragma once
33 
34 #include <forward_list>
35 #include <set>
36 #include <ogdf/basic/EpsilonTest.h>
38 #include <ogdf/graphalg/Voronoi.h>
41 #include <memory>
44 
45 #include <unordered_map>
46 
47 namespace ogdf {
48 
49 // Helpers:
50 namespace steiner_tree {
56 public:
57  int operator() (NodePair const &v) const
58  {
59  return static_cast<int>((static_cast<long long>(
60  min(v.source->index(), v.target->index())+11) * (max(v.source->index(), v.target->index())+73)) % 700001);
61  }
62 };
63 
69 public:
70  bool operator() (NodePair const &pair1, NodePair const &pair2) const
71  {
72  return (pair1.source == pair2.source && pair1.target == pair2.target)
73  || (pair1.source == pair2.target && pair1.target == pair2.source);
74  }
75 };
76 
77 } // end namespace steiner_tree
78 
79 
91 template<typename T>
93 protected:
98 
102 
104 
113  std::vector<std::vector<int>> m_sonsList;
114 
115  std::unique_ptr<MinSteinerTreeModule<T>> m_costUpperBoundAlgorithm;
116 
117  class HeavyPathDecomposition;
120 public:
121 
127  SteinerTreePreprocessing(const EdgeWeightedGraph<T> &wg, const List<node> &terminals, const NodeArray<bool> &isTerminal);
128 
137  {
138  finalSteinerTree = new EdgeWeightedGraphCopy<T>;
139  // reductions generate new nodes and edges, which may inflate the internal structure
140  if (m_copyGraph.maxNodeIndex() <= m_copyGraph.numberOfNodes() + 5
141  && m_copyGraph.maxEdgeIndex() <= m_copyGraph.numberOfEdges() + 10) { // within inflate tolerance
142  EdgeWeightedGraphCopy<T> *reducedSolution = nullptr;
143  T cost = mst.call(m_copyGraph, m_copyTerminals, m_copyIsTerminal, reducedSolution);
144  cost += costEdgesAlreadyInserted();
145  computeOriginalSolution(*reducedSolution, *finalSteinerTree);
146  delete reducedSolution;
147  return cost;
148  }
149 
150  // make a compact copy
151  EdgeWeightedGraph<T> ccGraph;
152  NodeArray<node> nCopy(m_copyGraph, nullptr);
153  EdgeArray<edge> eCopy(m_copyGraph, nullptr);
154  List<node> ccTerminals;
155  NodeArray<bool> ccIsTerminal(ccGraph, false);
156  for (node v : m_copyGraph.nodes) {
157  nCopy[v] = ccGraph.newNode();
158  }
159  for (edge e : m_copyGraph.edges) {
160  eCopy[e] = ccGraph.newEdge(nCopy[e->source()], nCopy[e->target()], m_copyGraph.weight(e));
161  }
162  for (node t : m_copyTerminals) {
163  const node tC = nCopy[t];
164  ccTerminals.pushBack(tC);
165  ccIsTerminal[tC] = true;
166  }
167 
168  // solve compact copy
169  EdgeWeightedGraphCopy<T> *ccSolution = nullptr;
170  T cost = mst.call(ccGraph, ccTerminals, ccIsTerminal, ccSolution);
171  cost += costEdgesAlreadyInserted();
172 
173  // get reduced and original solution from compact copy solution
174  EdgeWeightedGraphCopy<T> reducedSolution;
175  reducedSolution.createEmpty(m_copyGraph);
176  for (node v : m_copyGraph.nodes) {
177  if (ccSolution->copy(nCopy[v]) != nullptr) { // is in solution
178  reducedSolution.newNode(v);
179  }
180  }
181  for (edge e : m_copyGraph.edges) {
182  if (ccSolution->copy(eCopy[e]) != nullptr) { // is in solution
183  reducedSolution.newEdge(e, m_copyGraph.weight(e));
184  }
185  }
186  delete ccSolution;
187 
188  computeOriginalSolution(reducedSolution, *finalSteinerTree);
189  return cost;
190  }
191 
197  inline const EdgeWeightedGraph<T>& getReducedGraph() const { return m_copyGraph; }
199 
201  inline const List<node>& getReducedTerminals() const { return m_copyTerminals; }
202 
204  inline const NodeArray<bool>& getReducedIsTerminal() const { return m_copyIsTerminal; }
206 
212  inline T costEdgesAlreadyInserted() const { return m_costAlreadyInserted; }
214 
220  void computeOriginalSolution(const EdgeWeightedGraphCopy<T> &reducedGraphSolution, EdgeWeightedGraphCopy<T> &correspondingOriginalSolution);
222 
228 
231  {
232  return repeat([this]() {
233  bool changed = false;
234  changed |= degree2Test();
235  changed |= makeSimple();
236  changed |= deleteLeaves();
237  return changed;
238  });
239  }
240 
242  bool reduceFast()
243  {
244  const int k = 5; // for PTmTest
245  bool changed = deleteComponentsWithoutTerminals();
246  bool triviallyChanged = false;
247  changed |= repeat([this, &triviallyChanged, k]() {
248  bool innerChanged = false;
249  triviallyChanged = reduceTrivial();
250  // graph guaranteed to be simple and connected
251 
252  // precond: simple, connected
253  innerChanged |= NTDkTest(10, k);
254  // can occur: parallel edges
255 
256  // precond: connected
257 #if 0
258  // commented out because it is too expensive
259  innerChanged |= longEdgesTest();
260 #endif
261 
262  // precond: connected
263  innerChanged |= lowerBoundBasedNodeTest();
264 
265  // precond: connected
266  if (lowerBoundBasedEdgeTest()) {
267  // can occur: disconnected
268  deleteComponentsWithoutTerminals();
269  makeSimple(); // not necessary, but does not hurt (XXX)
270  innerChanged = true;
271  }
272 
273  // precond: connected
274  if (terminalDistanceTest()) {
275  // can occur: disconnected graph
276  deleteComponentsWithoutTerminals();
277  }
278 
279  // is not thaaat good but helps a little:
280  innerChanged |= PTmTest(k);
281  // can occur: parallel edges
282 
283  innerChanged |= repeat([this]() {
284  // precond: must be connected
285  bool innerInnerChanged = shortLinksTest();
286  // can occur: parallel edges, self-loops
287  makeSimple();
288 
289  // precond: loop-free, connected
290  innerInnerChanged |= nearestVertexTest();
291  // can occur: parallel edges, self-loops
292  return innerInnerChanged;
293  });
294  return innerChanged;
295  });
296  return changed | triviallyChanged;
297  }
298 
300 
306 
314  bool deleteLeaves();
315 
322  bool makeSimple();
323 
330  bool deleteComponentsWithoutTerminals();
331 
338  bool leastCostTest();
339 
346  bool degree2Test();
347 
355  bool PTmTest(const int k = 3);
356 
365  bool terminalDistanceTest();
366 
373  bool longEdgesTest();
374 
385  bool NTDkTest(const int maxTestedDegree = 5, const int k = 3);
386 
395  bool nearestVertexTest();
396 
405  bool shortLinksTest();
406 
417  bool lowerBoundBasedNodeTest();
418 
429  bool lowerBoundBasedEdgeTest();
430 
441  bool reachabilityTest(int maxDegreeTest = 0, const int k = 3);
442 
451  bool cutReachabilityTest();
452 
454 
460  inline void setCostUpperBoundAlgorithm(MinSteinerTreeModule<T> *pMinSteinerTreeModule) {
462  m_costUpperBoundAlgorithm.reset(pMinSteinerTreeModule);
463  }
464 
466 
467 private:
469  template<typename Fun>
470  bool repeat(Fun f) const
471  {
472  bool changed = false;
473  while (f()) {
474  changed = true;
475  }
476  return changed;
477  }
478 
479 protected:
482  {
484  EdgeArray<edge> bridges;
485  Voronoi<T> voronoi(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
486 
487  MinSteinerTreeMehlhorn<T>::calculateCompleteGraph(m_copyGraph, m_copyTerminals, voronoi, bridges, *terminalTree);
488 
489  makeMinimumSpanningTree(*terminalTree, terminalTree->edgeWeights());
490 
491  return terminalTree;
492  }
493 
502  template<typename TWhat, typename TWhatArray>
503  void addNew(TWhat x, const std::vector<node> &replacedNodes, const std::vector<edge> &replacedEdges, bool deleteReplacedElements,
504  TWhatArray &whatSonsListIndex);
505 
507  inline void addNewNode(node v, const std::vector<node> &replacedNodes, const std::vector<edge> &replacedEdges, bool deleteReplacedElements)
508  {
509  addNew(v, replacedNodes, replacedEdges, deleteReplacedElements, m_nodeSonsListIndex);
510  }
511 
513  inline void addNewEdge(edge e, const std::vector<node> &replacedNodes, const std::vector<edge> &replacedEdges, bool deleteReplacedElements)
514  {
515  addNew(e, replacedNodes, replacedEdges, deleteReplacedElements, m_edgeSonsListIndex);
516  }
517 
524  bool addEdgesToSolution(const List<edge> &edgesToBeAddedInSolution);
525 
527  void recomputeTerminalsList();
528 
530  void computeShortestPathMatrix(NodeArray<NodeArray<T>> &shortestPath) const;
531 
533  void floydWarshall(NodeArray<NodeArray<T>> &shortestPath) const;
534 
536  {
537  finalSteinerTree = nullptr;
538  return m_costUpperBoundAlgorithm->call(m_copyGraph, m_copyTerminals, m_copyIsTerminal, finalSteinerTree);
539  }
540 
541  // for convenience:
543  {
544  EdgeWeightedGraphCopy<T> *finalSteinerTree;
545  T treeCostUpperBound = computeMinSteinerTreeUpperBound(finalSteinerTree);
546  delete finalSteinerTree;
547  return treeCostUpperBound;
548  }
549 
551  void addToSolution(const int listIndex, Array<bool, int> &isInSolution) const;
552 
554  bool deleteNodesAboveUpperBound(const NodeArray<T> &lowerBoundWithNode, const T upperBound);
556  bool deleteEdgesAboveUpperBound(const EdgeArray<T> &lowerBoundWithEdge, const T upperBound);
557 
559  void deleteSteinerDegreeTwoNode(node v, const EdgeWeightedGraphCopy<T> &tprime, const HeavyPathDecomposition &tprimeHPD, const NodeArray<List<std::pair<node,T>>> &closestTerminals);
560 
570  void findClosestNonTerminals(node source, List<node> &reachedNodes, NodeArray<T> &distance, T maxDistance, int expandedEdges) const;
571 
576  T computeBottleneckDistance(node x, node y, const EdgeWeightedGraphCopy<T> &tprime, const HeavyPathDecomposition &tprimeHPD, const NodeArray<List<std::pair<node,T>>> &closestTerminals) const;
577 
583  void computeClosestKTerminals(const int k, NodeArray<List<std::pair<node,T>>> &closestTerminals) const;
584 
586  void computeRadiusOfTerminals(NodeArray<T> &terminalRadius) const;
587 
589  T computeRadiusSum() const;
590 
592  template<typename LAMBDA>
593  void computeOptimalTerminals(node v, LAMBDA dist, node &optimalTerminal1, node &optimalTerminal2, NodeArray<T> &distance) const;
594 
596  void markSuccessors(node currentNode, const Voronoi<T> &voronoiRegions, NodeArray<bool> &isSuccessorOfMinCostEdge) const;
597 };
598 
599 template<typename T>
601  : m_origGraph(wg)
602  , m_origTerminals(terminals)
603  , m_origIsTerminal(isTerminal)
604  , m_eps()
605 {
606  // make the initial graph copy
607  m_copyGraph.clear();
610 
611  for (node v : m_origGraph.nodes) {
612  nCopy[v] = m_copyGraph.newNode();
613  }
614  for (edge e : m_origGraph.edges) {
615  eCopy[e] = m_copyGraph.newEdge(nCopy[e->source()], nCopy[e->target()], m_origGraph.weight(e));
616  }
617 
618  // create the terminals and isTerminal arrays for the copyGraph
619  m_copyTerminals.clear();
621  for (node v : m_origGraph.nodes) {
622  if (m_origIsTerminal(v)) {
623  const node vC = nCopy[v];
624  m_copyTerminals.pushBack(vC);
625  m_copyIsTerminal[vC] = true;
626  }
627  }
629 
630  // map every node and edge to a negative number for m_(node/edge)_m_sonsListIndex
633  int nextIndex = 1;
634  for (node v : m_origGraph.nodes) {
635  m_nodeSonsListIndex[nCopy[v]] = -(nextIndex++);
636  }
637  for (edge e : m_origGraph.edges) {
638  m_edgeSonsListIndex[eCopy[e]] = -(nextIndex++);
639  }
640 
641  // set the default approximation algorithm for computing the upper bound cost of the solution
643 }
644 
645 template<typename T>
646 template<typename TWhat, typename TWhatArray>
648  const std::vector<node> &replacedNodes,
649  const std::vector<edge> &replacedEdges,
650  bool deleteReplacedElements,
651  TWhatArray &whatSonsListIndex)
652 {
653  std::vector<int> sonsIndexList;
654  for (node replacedNode : replacedNodes) {
655  sonsIndexList.push_back(m_nodeSonsListIndex[replacedNode]);
656  }
657  for (edge replacedEdge : replacedEdges) {
658  sonsIndexList.push_back(m_edgeSonsListIndex[replacedEdge]);
659  }
660 
661  m_sonsList.emplace_back(sonsIndexList);
662  whatSonsListIndex[x] = (int)m_sonsList.size() - 1;
663 
664  if (deleteReplacedElements) {
665  for (edge e : replacedEdges) {
666  m_copyGraph.delEdge(e);
667  }
668  for (node v :replacedNodes) {
669  m_copyGraph.delNode(v);
670  }
671  }
672 }
673 
674 template<typename T>
675 void SteinerTreePreprocessing<T>::addToSolution(const int listIndex, Array<bool, int>& isInSolution) const
676 {
677  if (listIndex < 0) { // is starting node or edge
678  isInSolution[listIndex] = true;
679  return;
680  }
681  // is further added node or edge
682  for (int son : m_sonsList[listIndex]) {
683  addToSolution(son, isInSolution);
684  }
685 }
686 
687 template<typename T>
688 void SteinerTreePreprocessing<T>::computeOriginalSolution(const EdgeWeightedGraphCopy<T> &reducedGraphSolution, EdgeWeightedGraphCopy<T> &correspondingOriginalSolution)
689 {
690  correspondingOriginalSolution.createEmpty(m_origGraph); // note that it is not cleared!
691 
692  Array<bool, int> isInSolution(-(m_origGraph.numberOfNodes() + m_origGraph.numberOfEdges()), -1, false);
693 
694  // make the indices of original nodes/edge true in isInSolution
695  for (node v : reducedGraphSolution.nodes) {
696  addToSolution(m_nodeSonsListIndex[reducedGraphSolution.original(v)], isInSolution);
697  }
698  for (edge e : reducedGraphSolution.edges) {
699  addToSolution(m_edgeSonsListIndex[reducedGraphSolution.original(e)], isInSolution);
700  }
701 
702  // insert nodes and edges
703  int nextIndex = 1;
704  for (node v : m_origGraph.nodes) {
705  if (isInSolution[-(nextIndex++)]) {
706  correspondingOriginalSolution.newNode(v);
707  }
708  }
709  for (edge e : m_origGraph.edges) {
710  if (isInSolution[-(nextIndex++)]) {
711  correspondingOriginalSolution.newEdge(e, m_origGraph.weight(e));
712  }
713  }
714 }
715 
716 template<typename T>
718  const EdgeWeightedGraphCopy<T> &tprime,
719  const HeavyPathDecomposition &tprimeHPD,
720  const NodeArray<List<std::pair<node,T>>> &closestTerminals)
721 {
722  struct NewEdgeData {
723  edge e1; // new edge replaces this...
724  edge e2; // ...and this
725  edge already; // but is it already there?
726  T weight;
727  };
728  std::forward_list<NewEdgeData> newEdges;
729  for (adjEntry adj1 : v->adjEntries) {
730  const edge e1 = adj1->theEdge();
731  const node adjacentNode1 = adj1->twinNode();
732 
733  for (adjEntry adj2 = adj1->succ(); adj2 ; adj2 = adj2->succ()) {
734  const edge e2 = adj2->theEdge();
735  const node adjacentNode2 = adj2->twinNode();
736 
737  T edgeWeight = m_copyGraph.weight(e1) + m_copyGraph.weight(e2);
738 
739  const edge f = m_copyGraph.searchEdge(adjacentNode1, adjacentNode2);
740  if (f && m_copyGraph.weight(f) <= edgeWeight) {
741  continue; // check whether there is already a lower cost edge connecting the two adjacent nodes
742  }
743 
744  T bottleneckDistance = computeBottleneckDistance(adjacentNode1, adjacentNode2, tprime, tprimeHPD, closestTerminals);
745  if (m_eps.greater(edgeWeight, bottleneckDistance)) {
746  continue; // the PTm test
747  }
748 
749  newEdges.emplace_front(NewEdgeData{e1, e2, f, edgeWeight});
750  }
751  }
752 
753  for (const auto &newEdge : newEdges) {
754  // delete the old edge (do not generate parallel edges)
755  edge newEdgeInGraph;
756  if (newEdge.already) {
757  OGDF_ASSERT(m_copyGraph.weight(newEdge.already) > newEdge.weight);
758  m_copyGraph.setWeight(newEdge.already, newEdge.weight);
759  newEdgeInGraph = newEdge.already;
760  } else {
761  newEdgeInGraph = m_copyGraph.newEdge(newEdge.e1->opposite(v), newEdge.e2->opposite(v), newEdge.weight);
762  }
763  addNewEdge(newEdgeInGraph, {v}, {newEdge.e1, newEdge.e2}, false);
764  }
765 
766  m_copyGraph.delNode(v);
767 }
768 
769 template<typename T>
771 {
772  m_copyTerminals.clear();
773  for (node v : m_copyGraph.nodes) {
774  if (m_copyIsTerminal[v]) {
775  m_copyTerminals.pushBack(v);
776  }
777  }
778 }
779 
780 template<typename T>
782  const EdgeWeightedGraphCopy<T> &tprime,
783  const HeavyPathDecomposition &tprimeHPD,
784  const NodeArray<List<std::pair<node, T>>> &closestTerminals) const
785 {
786  T bottleneckDistance = numeric_limits<T>::max();
787 
788  for (auto &xCloseTerminalDistancePair : closestTerminals[x]) {
789  for (auto &yCloseTerminalDistancePair : closestTerminals[y]) {
790  T possibleBottleneckDistance = xCloseTerminalDistancePair.second + yCloseTerminalDistancePair.second;
791 
792  node xTprimeCopy = tprime.copy(xCloseTerminalDistancePair.first);
793  node yTprimeCopy = tprime.copy(yCloseTerminalDistancePair.first);
794  possibleBottleneckDistance += tprimeHPD.getBottleneckSteinerDistance(xTprimeCopy, yTprimeCopy);
795 
796  bottleneckDistance = min(bottleneckDistance, possibleBottleneckDistance);
797  }
798  }
799 
800  return bottleneckDistance;
801 }
802 
803 template<typename T>
805 private:
809 
810  std::vector<std::vector<node>> chains;
811  std::vector<std::vector<node>> chainsOfTerminals;
818  std::vector<node> fatherOfChain;
819 
820  std::vector<std::vector<T>> longestDistToSteinerAncestorOnChain;
821  std::vector<std::vector<T>> longestDistToSteinerAncestorSegTree;
822 
827  void buildMaxSegmentTree(std::vector<T> &segmentTree, const int nodeIndex, const int left, const int right, const std::vector<T> &baseArray) const
828  {
829  if (left == right) { // leaf
830  segmentTree[nodeIndex] = baseArray[left];
831  return;
832  }
833 
834  int middle = (left+right)>>1;
835  int leftNodeIndex = nodeIndex+nodeIndex+1;
836  int rightNodeIndex = leftNodeIndex + 1;
837 
838  buildMaxSegmentTree(segmentTree, leftNodeIndex, left, middle, baseArray);
839  buildMaxSegmentTree(segmentTree, rightNodeIndex, middle+1, right, baseArray);
840 
841  segmentTree[nodeIndex] = max(segmentTree[leftNodeIndex], segmentTree[rightNodeIndex]);
842  }
847  T getMaxSegmentTree(const std::vector<T> &segmentTree, const int nodeIndex, const int left, const int right, const int queryLeft, const int queryRight) const
848  {
849  if (queryLeft > queryRight
850  || left > queryRight
851  || queryLeft > right) {
852  return 0;
853  }
854 
855  if (queryLeft <= left
856  && right <= queryRight) { // included
857  return segmentTree[nodeIndex];
858  }
859 
860  int middleIndex = (left + right)>>1;
861  int leftNodeIndex = nodeIndex+nodeIndex+1;
862  int rightNodeIndex = leftNodeIndex + 1;
863 
864  T maxValue(0);
865  if (queryLeft <= middleIndex) {
866  maxValue = max(maxValue, getMaxSegmentTree(segmentTree, leftNodeIndex, left, middleIndex, queryLeft, queryRight));
867  }
868  if (queryRight > middleIndex) {
869  maxValue = max(maxValue, getMaxSegmentTree(segmentTree, rightNodeIndex, middleIndex+1, right, queryLeft, queryRight));
870  }
871 
872  return maxValue;
873  }
874 
879  T distanceToAncestor(node v, node ancestor) const
880  {
881  if (ancestor == nullptr) {
882  return distanceToRoot[v];
883  }
884  return distanceToRoot[v] - distanceToRoot[ancestor];
885  }
886 
893  {
894  longestDistToSteinerAncestorOnChain.resize((int)chains.size());
895  for (int i = 0; i < (int)chains.size(); ++i) {
896  longestDistToSteinerAncestorOnChain[i].resize((int)chains[i].size());
897  for (int j = 0; j < (int)chains[i].size(); ++j) {
898  longestDistToSteinerAncestorOnChain[i][j] = distanceToAncestor(chains[i][j], closestSteinerAncestor[chains[i][j]]);
899  if (j > 0) {
900  longestDistToSteinerAncestorOnChain[i][j] = max(longestDistToSteinerAncestorOnChain[i][j], longestDistToSteinerAncestorOnChain[i][j-1]);
901  }
902  }
903  }
904  }
905 
912  {
913  longestDistToSteinerAncestorSegTree.resize((int)chains.size());
914  for (int i = 0; i < (int)chains.size(); ++i) {
915  longestDistToSteinerAncestorSegTree[i].resize(4*(int)chains[i].size());
916 
917  std::vector<T> distanceToSteinerAncestor_byPosition;
918  distanceToSteinerAncestor_byPosition.resize(chains[i].size());
919  for (int j = 0; j < (int)chains[i].size(); ++j) {
920  distanceToSteinerAncestor_byPosition[j] = distanceToAncestor(chains[i][j], closestSteinerAncestor[chains[i][j]]);
921  }
922 
923  buildMaxSegmentTree(longestDistToSteinerAncestorSegTree[i], 0, 0, (int)chains[i].size()-1, distanceToSteinerAncestor_byPosition);
924  }
925  }
926 
931  void dfsHeavyPathDecomposition(node v, node closestSteinerUpNode)
932  {
933  weightOfSubtree[v] = 1;
934  node heaviestSon = nullptr;
935  closestSteinerAncestor[v] = closestSteinerUpNode;
936 
937  for(adjEntry adj : v->adjEntries) {
938  edge e = adj->theEdge();
939  node son = adj->twinNode();
940 
941  if (weightOfSubtree[son] != 0) { // the parent
942  continue;
943  }
944 
945  nodeLevel[son] = nodeLevel[v] + 1;
946  distanceToRoot[son] = distanceToRoot[v] + tree.weight(e);
947 
948  dfsHeavyPathDecomposition(son, v);
949 
950  fatherOfChain[chainOfNode[son]] = v;
951  weightOfSubtree[v] += weightOfSubtree[son];
952  if (heaviestSon == nullptr
953  || weightOfSubtree[heaviestSon] < weightOfSubtree[son]) {
954  heaviestSon = son;
955  }
956  }
957 
958  if (heaviestSon == nullptr) { // it's leaf => new chain
959  OGDF_ASSERT((v->degree() <= 1));
960 
961  std::vector<node>new_chain;
962  chains.push_back(new_chain);
963  chainsOfTerminals.push_back(new_chain);
964 
965  fatherOfChain.push_back(nullptr);
966  chainOfNode[v] = (int)chains.size()-1;
967  } else {
968  chainOfNode[v] = chainOfNode[heaviestSon];
969  }
970 
971  chains[chainOfNode[v]].push_back(v);
972  chainsOfTerminals[chainOfNode[v]].push_back(v);
973  positionOnChain[v] = (int)chains[chainOfNode[v]].size()-1;
974  }
975 
981  node binarySearchUpmostTerminal(node v, const std::vector<node> &chainOfTerminals) const
982  {
983  int left = 0, middle, right = (int)chainOfTerminals.size()-1;
984  while (left <= right) {
985  middle = (left+right)>>1;
986 
987  if (nodeLevel[chainOfTerminals[middle]] >= nodeLevel[v]) {
988  right = middle-1;
989  } else {
990  left = middle+1;
991  }
992  }
993 
994  if (left == (int)chainOfTerminals.size()) {
995  return nullptr;
996  }
997  return chainOfTerminals[left];
998  }
999 
1009  void computeBottleneckOnBranch(node x, node ancestor, T &longestPathDistance, T &fromLowestToAncestor) const
1010  {
1011  node upmostTerminal = x;
1012  while (closestSteinerAncestor[chains[chainOfNode[x]][0]] != nullptr
1013  && nodeLevel[closestSteinerAncestor[chains[chainOfNode[x]][0]]] >= nodeLevel[ancestor]) {
1014  longestPathDistance = max(longestPathDistance, longestDistToSteinerAncestorOnChain[chainOfNode[x]][positionOnChain[x]]);
1015 
1016  if (!chainsOfTerminals[chainOfNode[x]].empty()
1017  && nodeLevel[chainsOfTerminals[chainOfNode[x]][0]] <= nodeLevel[x]) {
1018  upmostTerminal = chainsOfTerminals[chainOfNode[x]][0];
1019  }
1020  x = fatherOfChain[chainOfNode[x]];
1021  }
1022 
1023  // search the upmost terminal on the current chain that has level >= level[ancestor]
1024  node upmostTerminalLastChain = binarySearchUpmostTerminal(ancestor, chainsOfTerminals[chainOfNode[x]]);
1025  if (nodeLevel[upmostTerminalLastChain] > nodeLevel[x]) {
1026  upmostTerminalLastChain = nullptr;
1027  }
1028  if (upmostTerminalLastChain != nullptr) {
1029  upmostTerminal = upmostTerminalLastChain;
1030  }
1031 
1032  if (upmostTerminalLastChain != nullptr) {
1033  longestPathDistance = max(longestPathDistance,
1034  getMaxSegmentTree(longestDistToSteinerAncestorSegTree[chainOfNode[x]], 0, 0,
1035  static_cast<int>(chains[chainOfNode[x]].size()) - 1,
1036  positionOnChain[upmostTerminalLastChain] + 1,
1037  positionOnChain[x]));
1038  }
1039 
1040  fromLowestToAncestor = distanceToAncestor(upmostTerminal, ancestor);
1041  }
1042 
1043 public:
1044 
1046  : tree(treeEWGraphCopy)
1047  {
1048  node root = treeEWGraphCopy.firstNode();
1049 
1050  chainOfNode.init(treeEWGraphCopy, -1);
1051  positionOnChain.init(treeEWGraphCopy, -1);
1052  weightOfSubtree.init(treeEWGraphCopy, 0);
1053  nodeLevel.init(treeEWGraphCopy, 0);
1054  distanceToRoot.init(treeEWGraphCopy, 0);
1055  closestSteinerAncestor.init(treeEWGraphCopy, nullptr);
1056 
1057  dfsHeavyPathDecomposition(root, nullptr);
1058  fatherOfChain[chainOfNode[root]] = nullptr;
1059 
1060  // reverse the obtained chains
1061  int numberOfChains = static_cast<int>(chains.size());
1062  for (int i = 0; i < numberOfChains; ++i) {
1063  reverse(chains[i].begin(), chains[i].end());
1064  reverse(chainsOfTerminals[i].begin(), chainsOfTerminals[i].end());
1065  for (node v : chains[i]) {
1066  positionOnChain[v] = (int)chains[i].size()-1-positionOnChain[v];
1067  }
1068  }
1069 
1070  computeLongestDistToSteinerAncestorOnChain();
1071  computeLongestDistToSteinerAncestorSegTree();
1072  }
1073 
1079  {
1080  while (chainOfNode[x] != chainOfNode[y]) {
1081  int xlevelOfFatherOfChain = fatherOfChain[chainOfNode[x]] != nullptr ? nodeLevel[fatherOfChain[chainOfNode[x]]] : -1;
1082  int ylevelOfFatherOfChain = fatherOfChain[chainOfNode[y]] != nullptr ? nodeLevel[fatherOfChain[chainOfNode[y]]] : -1;
1083 
1084  if (xlevelOfFatherOfChain >= ylevelOfFatherOfChain) {
1085  x = fatherOfChain[chainOfNode[x]];
1086  } else {
1087  y = fatherOfChain[chainOfNode[y]];
1088  }
1089  }
1090 
1091  if (nodeLevel[x] <= nodeLevel[y]) {
1092  return x;
1093  }
1094  return y;
1095  }
1096 
1102  {
1103  T xLongestPathDistance = 0, yLongestPathDistance = 0;
1104  T xFromLowestToLCA = 0, yFromLowestToLCA = 0;
1105  node xyLowestCommonAncestor = lowestCommonAncestor(x, y);
1106 
1107  computeBottleneckOnBranch(x, xyLowestCommonAncestor, xLongestPathDistance, xFromLowestToLCA);
1108  computeBottleneckOnBranch(y, xyLowestCommonAncestor, yLongestPathDistance, yFromLowestToLCA);
1109 
1110  T maxValue = max(xLongestPathDistance, yLongestPathDistance);
1111  maxValue = max(maxValue, xFromLowestToLCA+yFromLowestToLCA);
1112 
1113  return maxValue;
1114  }
1115 };
1116 
1117 template<typename T>
1119 {
1120  // exceptional case: only one terminal
1121  auto deleteAll = [this]() {
1122  if (m_copyGraph.numberOfNodes() > 1) {
1123  const node w = m_copyTerminals.front();
1124  // just remove all other nodes
1125  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1126  nextV = v->succ();
1127  if (v != w) {
1128  m_copyGraph.delNode(v);
1129  }
1130  }
1131  return true;
1132  }
1133  return false;
1134  };
1135  if (m_copyTerminals.size() == 1) {
1136  return deleteAll();
1137  }
1138  // general case: at least 2 terminals
1139  BoundedQueue<node> eraseQueue(m_copyGraph.numberOfNodes());
1140 
1141  for (node v : m_copyGraph.nodes) {
1142  if (v->degree() == 1) {
1143  eraseQueue.append(v);
1144  }
1145  }
1146 
1147  if (eraseQueue.empty()) {
1148  return false;
1149  }
1150 
1151  for (; !eraseQueue.empty(); eraseQueue.pop()) {
1152  node v = eraseQueue.top();
1153  if (v->degree() == 0) {
1154  continue;
1155  }
1156  OGDF_ASSERT(v->degree() == 1);
1157  const node w = v->firstAdj()->twinNode();
1158  if (m_copyIsTerminal[v]) { // v is a terminal
1159  // add edge to solution and contract v into w
1160  edge e = v->firstAdj()->theEdge();
1161  if (!m_copyIsTerminal[w]) {
1162  m_copyIsTerminal[w] = true;
1163  m_copyTerminals.pushBack(w);
1164  }
1165  m_copyTerminals.del(m_copyTerminals.search(v));
1166  m_costAlreadyInserted += m_copyGraph.weight(e);
1167  int cur = m_nodeSonsListIndex[w];
1168  if (cur < 0) { // w is an original (copied) node
1169  m_sonsList.emplace_back(std::vector<int>{cur, m_nodeSonsListIndex[v], m_edgeSonsListIndex[e]});
1170  m_nodeSonsListIndex[w] = (int)m_sonsList.size() - 1;
1171  } else { // w contains already sons
1172  m_sonsList[cur].push_back(m_nodeSonsListIndex[v]);
1173  m_sonsList[cur].push_back(m_edgeSonsListIndex[e]);
1174  }
1175  } else { // v is not a terminal
1176  if (w->degree() == 2) {
1177  eraseQueue.append(w);
1178  }
1179  }
1180  m_copyGraph.delNode(v);
1181  if (m_copyTerminals.size() == 1) {
1182  deleteAll();
1183  return true;
1184  }
1185  }
1186  return true;
1187 }
1188 
1189 template<typename T>
1191 {
1192  bool changed = false;
1193  NodeArray<edge> minCostEdge(m_copyGraph, nullptr);
1194  for (node v : m_copyGraph.nodes) {
1195  for (adjEntry adj = v->firstAdj(), nextAdj; adj; adj = nextAdj) {
1196  nextAdj = adj->succ();
1197 
1198  edge e = adj->theEdge();
1199  node adjNode = adj->twinNode();
1200  if (adjNode == v) { // found a self-loop
1201  if (nextAdj == adj->twin()) {
1202  nextAdj = nextAdj->succ();
1203  }
1204  m_copyGraph.delEdge(e);
1205  changed = true;
1206  } else {
1207  if (minCostEdge[adjNode] == nullptr
1208  || m_copyGraph.weight(minCostEdge[adjNode]) > m_copyGraph.weight(e)) {
1209  if (minCostEdge[adjNode] != nullptr) {
1210  m_copyGraph.delEdge(minCostEdge[adjNode]);
1211  changed = true;
1212  }
1213  minCostEdge[adjNode] = e;
1214  } else {
1215  m_copyGraph.delEdge(e);
1216  changed = true;
1217  }
1218  }
1219  }
1220 
1221  for(adjEntry adj : v->adjEntries) {
1222  minCostEdge[adj->twinNode()] = nullptr;
1223  }
1224  }
1225  return changed;
1226 }
1227 
1228 template<typename T>
1230 {
1231  for (node v1 : m_copyGraph.nodes) {
1232  for(adjEntry adj : v1->adjEntries) {
1233  node v2 = adj->twinNode();
1234  shortestPath[v1][v2] = shortestPath[v2][v1] = min(shortestPath[v1][v2], m_copyGraph.weight(adj->theEdge()));
1235  }
1236  }
1237 
1238  for (node pivot : m_copyGraph.nodes) {
1239  for (node v1 : m_copyGraph.nodes) {
1240  for (node v2 : m_copyGraph.nodes) {
1241  if (shortestPath[v1][pivot] == numeric_limits<T>::max()
1242  || shortestPath[pivot][v2] == numeric_limits<T>::max()) {
1243  continue;
1244  }
1245 
1246  shortestPath[v1][v2] = min(shortestPath[v1][v2], shortestPath[v1][pivot] + shortestPath[pivot][v2]);
1247  }
1248  }
1249  }
1250 }
1251 
1252 template<typename T>
1254 {
1255  shortestPath.init(m_copyGraph);
1256  for (node v : m_copyGraph.nodes) {
1257  shortestPath[v].init(m_copyGraph, numeric_limits<T>::max());
1258  }
1259 
1260  floydWarshall(shortestPath);
1261 }
1262 
1263 template<typename T>
1265 {
1266  bool changed = false;
1267  NodeArray<NodeArray<T>> shortestPath;
1268  computeShortestPathMatrix(shortestPath);
1269 
1270  for (node v : m_copyGraph.nodes) {
1271  for (adjEntry adj = v->firstAdj(), nextAdj; adj; adj = nextAdj) {
1272  nextAdj = adj->succ();
1273 
1274  edge e = adj->theEdge();
1275  node adjNode = adj->twinNode();
1276  if (adjNode != v
1277  && shortestPath[v][adjNode] < m_copyGraph.weight(e)) {
1278  m_copyGraph.delEdge(e);
1279  changed = true;
1280  }
1281  }
1282  }
1283  return changed;
1284 }
1285 
1286 template<typename T>
1288 {
1289  bool changed = false;
1290  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1291  nextV = v->succ();
1292 
1293  if (m_copyIsTerminal[v]
1294  || v->degree() != 2 ) {
1295  continue;
1296  }
1297 
1298  // get left and right adjacent nodes
1299  edge eLeft = v->firstAdj()->theEdge();
1300  edge eRight = v->lastAdj()->theEdge();
1301 
1302  node vLeft = v->firstAdj()->twinNode();
1303  node vRight = v->lastAdj()->twinNode();
1304  if (vLeft != vRight) {
1305  T weight = m_copyGraph.weight(eLeft) + m_copyGraph.weight(eRight);
1306  edge newEdge = m_copyGraph.newEdge(vLeft, vRight, weight);
1307  addNewEdge(newEdge, {v}, {eLeft, eRight}, true);
1308  changed = true;
1309  } else { // v is leaf with parallel edges or self-loop component
1310  m_copyGraph.delNode(v);
1311  }
1312  }
1313  return changed;
1314 }
1315 
1316 template<typename T>
1318 {
1319  NodeArray<int> hisConnectedComponent(m_copyGraph, -1);
1320  bool changed = connectedComponents(m_copyGraph, hisConnectedComponent) > 1;
1321  if (changed) {
1322  int componentWithTerminals = -1;
1323  for (node v : m_copyTerminals) {
1324  if (componentWithTerminals != -1
1325  && hisConnectedComponent[v] != componentWithTerminals) {
1326  cerr << "terminals in different connected components!\n";
1327  OGDF_ASSERT(false);
1328  }
1329  componentWithTerminals = hisConnectedComponent[v];
1330  }
1331 
1332  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1333  nextV = v->succ();
1334  if (hisConnectedComponent[v] != componentWithTerminals) {
1335  m_copyGraph.delNode(v);
1336  }
1337  }
1338  }
1339  return changed;
1340 }
1341 
1342 template<typename T>
1344 {
1345  bool changed = false;
1347 
1349  T maxBottleneck(0);
1350  for (edge e : tprime->edges) {
1351  maxBottleneck = max(maxBottleneck, tprime->weight(e));
1352  }
1353  delete tprime;
1354 
1355  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1356  nextE = e->succ();
1357 
1358  if (m_eps.greater(m_copyGraph.weight(e), maxBottleneck)) {
1359  m_copyGraph.delEdge(e);
1360  changed = true;
1361  }
1362  }
1363 
1364  return changed;
1365 }
1366 
1367 template<typename T>
1368 void SteinerTreePreprocessing<T>::findClosestNonTerminals(node source, List<node> &reachedNodes, NodeArray<T> &distance, T maxDistance, int expandedEdges) const
1369 {
1371 
1372  // initialization
1373  distance[source] = 0;
1374  queue.push(source, distance[source]);
1375 
1376  while (!queue.empty()) {
1377  node currentNode = queue.topElement();
1378  queue.pop();
1379 
1380  reachedNodes.pushBack(currentNode);
1381 
1382  for(adjEntry adj : currentNode->adjEntries) {
1383  edge e = adj->theEdge();
1384  if (expandedEdges <= 0) {
1385  break;
1386  }
1387  --expandedEdges;
1388 
1389  node adjacentNode = e->opposite(currentNode);
1390  T possibleDistance = distance[currentNode] + m_copyGraph.weight(e);
1391 
1392  if (m_eps.geq(possibleDistance, maxDistance)
1393  || m_copyIsTerminal[adjacentNode]) {
1394  continue;
1395  }
1396 
1397  if (possibleDistance < distance[adjacentNode]) {
1398  distance[adjacentNode] = possibleDistance;
1399  if (queue.contains(adjacentNode)) { // is already in the queue
1400  queue.decrease(adjacentNode, possibleDistance);
1401  } else {
1402  queue.push(adjacentNode, distance[adjacentNode]);
1403  }
1404  }
1405  }
1406  }
1407 }
1408 
1409 template<typename T>
1411 {
1412  bool changed = false;
1413  NodeArray<T> xDistance(m_copyGraph, numeric_limits<T>::max()),
1414  yDistance(m_copyGraph, numeric_limits<T>::max());
1415 
1416  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1417  nextE = e->succ();
1418  List<node> xReachedNodes, yReachedNodes;
1419 
1420  findClosestNonTerminals(e->source(), xReachedNodes, xDistance, m_copyGraph.weight(e), 200);
1421  findClosestNonTerminals(e->target(), yReachedNodes, yDistance, m_copyGraph.weight(e), 200);
1422 
1423  for (node commonNode : xReachedNodes) {
1424  if (yDistance[commonNode] == numeric_limits<T>::max()) { // is not common
1425  continue;
1426  }
1427  if (m_eps.less(xDistance[commonNode] + yDistance[commonNode], m_copyGraph.weight(e))) {
1428  m_copyGraph.delEdge(e);
1429  changed = true;
1430  break;
1431  }
1432  }
1433 
1434  for (node reachedNode : xReachedNodes) {
1435  xDistance[reachedNode] = numeric_limits<T>::max();
1436  }
1437  for (node reachedNode : yReachedNodes) {
1438  yDistance[reachedNode] = numeric_limits<T>::max();
1439  }
1440  }
1441  return changed;
1442 }
1443 
1444 template<typename T>
1445 void SteinerTreePreprocessing<T>::computeClosestKTerminals(const int k, NodeArray<List<std::pair<node,T>>> &closestTerminals) const
1446 {
1447  using NodePairQueue = PrioritizedQueue<NodePair, T>;
1448 
1449  closestTerminals.init(m_copyGraph);
1450  NodePairQueue queue;
1451  std::unordered_map<NodePair, typename NodePairQueue::Handle, steiner_tree::UnorderedNodePairHasher, steiner_tree::UnorderedNodePairEquality> qpos;
1452 
1453  // initialization
1454  for (node v : m_copyTerminals) {
1455  closestTerminals[v].pushBack(std::make_pair(v, 0));
1456  qpos[NodePair(v, v)] = queue.push(NodePair(v, v), closestTerminals[v].front().second);
1457  }
1458 
1459  auto getCurrentDist = [&closestTerminals](const node currentNode, const node sourceTerminal) {
1460  for (std::pair<node,T> currentPair : closestTerminals[currentNode]) {
1461  if (currentPair.first == sourceTerminal) {
1462  return currentPair.second;
1463  }
1464  }
1465  return static_cast<T>(-1);
1466  };
1467 
1468  auto setNewDist = [&closestTerminals, k](const node currentNode, const node sourceTerminal, const T newDist) {
1469  List<std::pair<node, T>> &currentList = closestTerminals[currentNode];
1470 
1471  // delete the old distance
1472  for (ListIterator<std::pair<node, T>> it = currentList.begin(); it.valid(); ++it) {
1473  if ((*it).first == sourceTerminal) {
1474  currentList.del(it);
1475  break;
1476  }
1477  }
1478 
1479  if (currentList.size() == k) { // the list is full
1480  currentList.popBack(); // delete the largest cost element
1481  }
1482 
1483  // add the new distance such that the list remains sorted
1484  if (currentList.empty()
1485  || (*(currentList.begin())).second >= newDist) { // if the list is empty
1486  currentList.pushFront(std::make_pair(sourceTerminal, newDist));
1487  return;
1488  }
1489 
1490  ListIterator<std::pair<node, T>> it = closestTerminals[currentNode].begin();
1491  while (it.succ() != closestTerminals[currentNode].end()
1492  && (*(it.succ())).second < newDist) {
1493  ++it;
1494  }
1495  closestTerminals[currentNode].insertAfter(std::make_pair(sourceTerminal, newDist), it);
1496  };
1497 
1498  while (!queue.empty()) {
1499  NodePair minDistPair = queue.topElement();
1500  queue.pop();
1501  node currentNode = minDistPair.source;
1502  node sourceTerminal = minDistPair.target;
1503 
1504  T currentDist = getCurrentDist(currentNode, sourceTerminal);
1505  if (currentDist == -1) { // source terminal not found
1506  continue; // check if the current path needs to be expanded
1507  }
1508 
1509  for(adjEntry adj : currentNode->adjEntries) {
1510  edge e = adj->theEdge();
1511  node adjacentNode = e->opposite(currentNode);
1512 
1513  if (m_copyIsTerminal[adjacentNode]) {
1514  continue;
1515  }
1516 
1517  T possibleNewDistance = currentDist + m_copyGraph.weight(e);
1518 
1519  // try to insert the new path from sourceTerminal to adjacentNode
1520  T currentDistToAdjacentNode = getCurrentDist(adjacentNode, sourceTerminal);
1521  if (currentDistToAdjacentNode != -1) { // there is already one path from sourceTerminal to adjNode
1522  if (possibleNewDistance < currentDistToAdjacentNode) {
1523  queue.decrease(qpos[NodePair(adjacentNode, sourceTerminal)], possibleNewDistance);
1524  setNewDist(adjacentNode, sourceTerminal, possibleNewDistance);
1525  }
1526  } else {
1527  if (closestTerminals[adjacentNode].size() < k
1528  || closestTerminals[adjacentNode].back().second > possibleNewDistance) {
1529  qpos[NodePair(adjacentNode, sourceTerminal)] = queue.push(NodePair(adjacentNode, sourceTerminal), possibleNewDistance);
1530  setNewDist(adjacentNode, sourceTerminal, possibleNewDistance);
1531  }
1532  }
1533  }
1534  }
1535 }
1536 
1537 template<typename T>
1539 {
1540  bool changed = false;
1542 
1544 
1545  NodeArray<List<std::pair<node,T>>> closestTerminals;
1546  computeClosestKTerminals(k, closestTerminals);
1547 
1548  HeavyPathDecomposition tprimeHPD(*tprime);
1549 
1550  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1551  nextE = e->succ();
1552 
1553  T bottleneckDistance = computeBottleneckDistance(e->source(), e->target(), *tprime, tprimeHPD, closestTerminals);
1554 
1555  if (m_eps.greater(m_copyGraph.weight(e), bottleneckDistance)) {
1556  m_copyGraph.delEdge(e);
1557  changed = true;
1558  }
1559  }
1560 
1561  delete tprime;
1562  return changed;
1563 }
1564 
1565 template<typename T>
1566 bool SteinerTreePreprocessing<T>::NTDkTest(const int maxTestedDegree, const int k)
1567 {
1568  if (m_copyTerminals.size() <= 2) {
1569  return false;
1570  }
1571 
1572  bool changed = false;
1575 
1577 
1578  NodeArray<List<std::pair<node,T>>> closestTerminals;
1579  computeClosestKTerminals(k, closestTerminals);
1580 
1581  HeavyPathDecomposition tprimeHPD(*tprime);
1582 
1583  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1584  nextV = v->succ();
1585 
1586  if (m_copyIsTerminal[v]) {
1587  continue;
1588  }
1589  if (v->degree() <= 2
1590  || v->degree() > maxTestedDegree) {
1591  continue;
1592  }
1593 
1594  // collect neighbors
1595  List<adjEntry> outgoingAdjs;
1596  for (adjEntry adj : v->adjEntries) {
1597  outgoingAdjs.pushBack(adj);
1598  }
1599  SubsetEnumerator<adjEntry> neighborSubset(outgoingAdjs);
1600 
1601  bool deleteNode = true;
1602  for (neighborSubset.begin(3, v->degree()); neighborSubset.valid() && deleteNode; neighborSubset.next()) {
1603  Graph auxGraph;
1604  std::unordered_map<node, node> initNodeToAuxGraph;
1605  std::unordered_map<node, node> auxGraphToInitNode;
1606 
1607  T sumToSelectedAdjacentNodes = 0;
1608 
1609  for (int i = 0; i < neighborSubset.size(); ++i) {
1610  const adjEntry adj = neighborSubset[i];
1611  const node adjacentNode = adj->twinNode();
1612  sumToSelectedAdjacentNodes += m_copyGraph.weight(adj->theEdge());
1613 
1614  OGDF_ASSERT(initNodeToAuxGraph.find(adjacentNode) == initNodeToAuxGraph.end());
1615 
1616  node newAuxGraphNode = auxGraph.newNode();
1617  initNodeToAuxGraph[adjacentNode] = newAuxGraphNode;
1618  auxGraphToInitNode[newAuxGraphNode] = adjacentNode;
1619  }
1620 
1621  EdgeArray<T> weight(auxGraph, 0);
1622  for (node auxGraphNode1 : auxGraph.nodes) {
1623  for (node auxGraphNode2 = auxGraphNode1->succ(); auxGraphNode2; auxGraphNode2 = auxGraphNode2->succ()) {
1624  edge e = auxGraph.newEdge(auxGraphNode1, auxGraphNode2);
1625  weight[e] = computeBottleneckDistance(
1626  auxGraphToInitNode[auxGraphNode1],
1627  auxGraphToInitNode[auxGraphNode2],
1628  *tprime, tprimeHPD, closestTerminals);
1629  }
1630  }
1631 
1632  // the auxGraph is now created; run MST on it
1633  EdgeArray<bool> isInTree(auxGraph, false);
1634  T mstCost = computeMinST(auxGraph, weight, isInTree);
1635 
1636  if (sumToSelectedAdjacentNodes < mstCost) {
1637  deleteNode = false;
1638  }
1639  }
1640 
1641  if (deleteNode) {
1642  deleteSteinerDegreeTwoNode(v, *tprime, tprimeHPD, closestTerminals);
1643  changed = true;
1644  }
1645  }
1646 
1647  delete tprime;
1648  return changed;
1649 }
1650 
1651 template<typename T>
1652 void SteinerTreePreprocessing<T>::markSuccessors(node currentNode, const Voronoi<T> &voronoiRegions, NodeArray<bool> &isSuccessorOfMinCostEdge) const
1653 {
1654  isSuccessorOfMinCostEdge[currentNode] = true;
1655 
1656  OGDF_ASSERT(voronoiRegions.seed(currentNode) != currentNode);
1657 
1658  for(adjEntry adj : currentNode->adjEntries) {
1659  edge e = adj->theEdge();
1660  node adjacentNode = e->opposite(currentNode);
1661 
1662  if (voronoiRegions.predecessor(adjacentNode) == currentNode) {
1663  markSuccessors(adjacentNode, voronoiRegions, isSuccessorOfMinCostEdge);
1664  }
1665  }
1666 }
1667 
1668 template<typename T>
1670 {
1671  if (edgesToBeAddedInSolution.empty()) {
1672  return false;
1673  }
1674  for (edge e : edgesToBeAddedInSolution) {
1675  node x = e->source(), y = e->target();
1676  m_sonsList.emplace_back(std::vector<int>{m_nodeSonsListIndex[x], m_nodeSonsListIndex[y], m_edgeSonsListIndex[e]});
1677  m_costAlreadyInserted += m_copyGraph.weight(e);
1678  node newNode = m_copyGraph.contract(e);
1679  m_nodeSonsListIndex[newNode] = (int)m_sonsList.size() - 1;
1680  m_copyIsTerminal[newNode] = true;
1681  }
1682 
1684  return true;
1685 }
1686 
1687 template<typename T>
1689 {
1692 
1693  Voronoi<T> voronoiRegions(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
1694 
1695  NodeArray<edge> minCostIncidentEdge1(m_copyGraph, nullptr);
1696  NodeArray<edge> minCostIncidentEdge2(m_copyGraph, nullptr);
1697 
1698  for (node terminal : m_copyTerminals) {
1699  if (terminal->degree() < 2) {
1700  continue;
1701  }
1702 
1703  // compute his two lowest cost incident edges
1704  for(adjEntry adj : terminal->adjEntries) {
1705  edge e = adj->theEdge();
1706  if (minCostIncidentEdge1[terminal] == nullptr
1707  || m_copyGraph.weight(minCostIncidentEdge1[terminal]) > m_copyGraph.weight(e)) {
1708  minCostIncidentEdge2[terminal] = minCostIncidentEdge1[terminal];
1709  minCostIncidentEdge1[terminal] = e;
1710  } else {
1711  if (minCostIncidentEdge2[terminal] == nullptr
1712  || m_copyGraph.weight(minCostIncidentEdge2[terminal]) > m_copyGraph.weight(e)) {
1713  minCostIncidentEdge2[terminal] = e;
1714  }
1715  }
1716  }
1717  }
1718 
1719  // mark nodes that have the first min cost incident node predecessor in the Voronoi tree
1720  NodeArray<bool> isSuccessorOfMinCostEdge(m_copyGraph, false);
1721  for (node terminal : m_copyTerminals) {
1722  if (terminal->degree() < 2) {
1723  continue;
1724  }
1725  node closestNode = minCostIncidentEdge1[terminal]->opposite(terminal);
1726 
1727  if (voronoiRegions.seed(closestNode) == terminal) {
1728  markSuccessors(closestNode, voronoiRegions, isSuccessorOfMinCostEdge);
1729  }
1730  }
1731 
1732  // compute for every terminal the distance to the closest terminal
1733  NodeArray<T> distanceToClosestTerminal(m_copyGraph, numeric_limits<T>::max());
1734  for (edge e : m_copyGraph.edges) {
1735  node x = e->source(), y = e->target();
1736  node seedX = voronoiRegions.seed(x), seedY = voronoiRegions.seed(y);
1737  if (seedX != seedY) {
1738  // update distanceToClosestTerminal for seed(x)
1739  T distanceThroughE = voronoiRegions.distance(x) + m_copyGraph.weight(e) + voronoiRegions.distance(y);
1740 
1741  if (isSuccessorOfMinCostEdge[x]) {
1742  distanceToClosestTerminal[seedX] = min(distanceToClosestTerminal[seedX],distanceThroughE);
1743  }
1744  if (isSuccessorOfMinCostEdge[y]) {
1745  distanceToClosestTerminal[seedY] = min(distanceToClosestTerminal[seedY],distanceThroughE);
1746  }
1747  }
1748  }
1749 
1750  // see what edges can be added in solution
1751  List<edge> edgesToBeAddedInSolution;
1752  EdgeArray<bool> willBeAddedInSolution(m_copyGraph, false);
1753  for (node terminal : m_copyTerminals) {
1754  if (terminal->degree() < 2) {
1755  continue;
1756  }
1757 
1758  const edge e1 = minCostIncidentEdge1[terminal];
1759  const node closestAdjacentNode = e1->opposite(terminal);
1760  T distance;
1761 
1762  if (voronoiRegions.seed(closestAdjacentNode) == terminal) {
1763  distance = distanceToClosestTerminal[terminal];
1764  } else {
1765  distance = m_copyGraph.weight(e1) + voronoiRegions.distance(closestAdjacentNode);
1766  }
1767  if (m_eps.geq(m_copyGraph.weight(minCostIncidentEdge2[terminal]), distance)
1768  && !willBeAddedInSolution[e1]) {
1769  edgesToBeAddedInSolution.pushBack(e1);
1770  willBeAddedInSolution[e1] = true;
1771  }
1772  }
1773 
1774  return addEdgesToSolution(edgesToBeAddedInSolution);
1775 }
1776 
1777 template<typename T>
1779 {
1781 
1782  Voronoi<T> voronoiRegions(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
1783 
1784  NodeArray<edge> minCostLeavingRegionEdge1(m_copyGraph, nullptr);
1785  NodeArray<edge> minCostLeavingRegionEdge2(m_copyGraph, nullptr);
1786 
1787  // populate minCostLeavingRegions{1,2}
1788  for (edge e : m_copyGraph.edges) {
1789  auto updateMinCostLeavingRegionsFor = [&](node seed) {
1790  if (minCostLeavingRegionEdge1[seed] == nullptr
1791  || m_copyGraph.weight(minCostLeavingRegionEdge1[seed]) > m_copyGraph.weight(e)) {
1792  minCostLeavingRegionEdge2[seed] = minCostLeavingRegionEdge1[seed];
1793  minCostLeavingRegionEdge1[seed] = e;
1794  } else
1795  if (minCostLeavingRegionEdge2[seed] == nullptr
1796  || m_copyGraph.weight(minCostLeavingRegionEdge2[seed]) > m_copyGraph.weight(e)) {
1797  minCostLeavingRegionEdge2[seed] = e;
1798  }
1799  };
1800  const node x = e->source(), y = e->target();
1801  const node seedX = voronoiRegions.seed(x), seedY = voronoiRegions.seed(y);
1802  if (seedX != seedY) { // e is a link between Voronoi regions
1803  // update minCostLeavingRegions for both x and y
1804  updateMinCostLeavingRegionsFor(seedX);
1805  updateMinCostLeavingRegionsFor(seedY);
1806  }
1807  }
1808 
1809  List<edge> edgesToBeAddedInSolution;
1810  EdgeArray<bool> willBeAddedInSolution(m_copyGraph, false);
1811  for (node terminal : m_copyTerminals) {
1812  if (minCostLeavingRegionEdge2[terminal] == nullptr) {
1813  continue;
1814  }
1815  // XXX: hm, is that smart? If there is no second shortest edge, then the first shortest edge belongs to the solution, doesn't it?
1816 
1817  const edge e1 = minCostLeavingRegionEdge1[terminal];
1818  const node x = e1->source(), y = e1->target();
1819  if (m_eps.geq(m_copyGraph.weight(minCostLeavingRegionEdge2[terminal]),
1820  voronoiRegions.distance(x) + m_copyGraph.weight(e1) + voronoiRegions.distance(y))
1821  && !willBeAddedInSolution[e1]) {
1822  edgesToBeAddedInSolution.pushBack(e1);
1823  willBeAddedInSolution[e1] = true;
1824  }
1825  }
1826 
1827  return addEdgesToSolution(edgesToBeAddedInSolution);
1828 }
1829 
1830 template<typename T>
1832 {
1833  // compute the Voronoi regions
1834  Voronoi<T> voronoiRegions(m_copyGraph, m_copyGraph.edgeWeights(), m_copyTerminals);
1835 
1836  // compute the radius for each terminal
1837  terminalRadius.init(m_copyGraph, numeric_limits<T>::max());
1838  for (node v : m_copyGraph.nodes) {
1839  node seedV = voronoiRegions.seed(v);
1840  T distanceToSeedV = voronoiRegions.distance(v);
1841 
1842  for(adjEntry adj : v->adjEntries) {
1843  edge e = adj->theEdge();
1844  node adjacentNode = e->opposite(v);
1845 
1846  if (voronoiRegions.seed(adjacentNode) != seedV) {
1847  terminalRadius[seedV] = min(terminalRadius[seedV], distanceToSeedV + m_copyGraph.weight(e));
1848  }
1849  }
1850  }
1851 }
1852 
1853 template<typename T>
1854 bool SteinerTreePreprocessing<T>::deleteNodesAboveUpperBound(const NodeArray<T> &lowerBoundWithNode, const T upperBound)
1855 {
1856  bool changed = false;
1857  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
1858  nextV = v->succ();
1859  if (m_eps.greater(lowerBoundWithNode[v], upperBound)) {
1860  m_copyGraph.delNode(v);
1861  changed = true;
1862  }
1863  }
1864  return changed;
1865 }
1866 
1867 template<typename T>
1869 {
1871 
1872  NodeArray<T> lowerBoundWithNode(m_copyGraph, numeric_limits<T>::lowest());
1873 
1874  NodeArray<List<std::pair<node, T>>> closestTerminals;
1875  computeClosestKTerminals(3, closestTerminals);
1876 
1877  // Update the lowerbound of the cost of a Steiner tree containing one particular node
1878  // as explained in [PV01, page 278, Observation 3.5]
1879  const T radiusSum = computeRadiusSum();
1880  for (node v : m_copyGraph.nodes) {
1881  if (m_copyIsTerminal[v]) {
1882  continue;
1883  }
1884 
1885  if (closestTerminals[v].size() < 2) {
1886  lowerBoundWithNode[v] = numeric_limits<T>::max();
1887  continue;
1888  }
1889 
1890  std::pair<node, T> closestTerminalPair1 = *(closestTerminals[v].get(0)), closestTerminalPair2 = *(closestTerminals[v].get(1));
1891  T distanceToClosestTerminal1 = closestTerminalPair1.second, distanceToClosestTerminal2 = closestTerminalPair2.second;
1892 
1893  lowerBoundWithNode[v] = max(lowerBoundWithNode[v], distanceToClosestTerminal1 + distanceToClosestTerminal2 + radiusSum);
1894  }
1895 
1896  // Update the lowerbound of the cost of a Steiner tree containing one particular node
1897  // as explained in [PV01, pages 279-280, Observation 3.8]
1898  Graph auxiliaryGraph;
1899  NodeArray<node> terminalInAuxiliaryGraph(m_copyGraph, nullptr);
1900  for (node terminal : m_copyTerminals) {
1901  node newAuxiliaryNode = auxiliaryGraph.newNode();
1902  terminalInAuxiliaryGraph[terminal] = newAuxiliaryNode;
1903  }
1904 
1905  EdgeArray<T> initialEdgeWeight(m_copyGraph);
1906  for (edge e : m_copyGraph.edges) {
1907  initialEdgeWeight[e] = m_copyGraph.weight(e);
1908  }
1909  Voronoi<T> voronoiRegions(m_copyGraph, initialEdgeWeight, m_copyTerminals);
1910 
1911  std::unordered_map<NodePair, edge, steiner_tree::UnorderedNodePairHasher, steiner_tree::UnorderedNodePairEquality> edgeBetweenNodes;
1912  EdgeArray<T> edgeWeight(auxiliaryGraph, numeric_limits<T>::max());
1913  for (edge e : m_copyGraph.edges) {
1914  node x = e->source(), y = e->target();
1915  node seedX = voronoiRegions.seed(x), seedY = voronoiRegions.seed(y);
1916  if (seedX == seedY) {
1917  continue;
1918  }
1919 
1920  auto pair = NodePair(terminalInAuxiliaryGraph[seedX], terminalInAuxiliaryGraph[seedY]);
1921  if (edgeBetweenNodes.find(pair) == edgeBetweenNodes.end()) {
1922  edgeBetweenNodes[pair] = auxiliaryGraph.newEdge(terminalInAuxiliaryGraph[seedX], terminalInAuxiliaryGraph[seedY]);
1923  }
1924  edge auxiliaryEdge = edgeBetweenNodes[pair];
1925  edgeWeight[auxiliaryEdge] = min(edgeWeight[auxiliaryEdge], min(voronoiRegions.distance(x), voronoiRegions.distance(y)) + m_copyGraph.weight(e));
1926  }
1927 
1928  EdgeArray<bool> isInTree(auxiliaryGraph, false);
1929  T minimumSpanningTreeCost = computeMinST(auxiliaryGraph, edgeWeight, isInTree);
1930  T longestEdgeCost = numeric_limits<T>::lowest();
1931  for (edge e : auxiliaryGraph.edges) {
1932  if (isInTree[e]) {
1933  longestEdgeCost = max(longestEdgeCost, edgeWeight[e]);
1934  }
1935  }
1936 
1937  for (node v : m_copyGraph.nodes) {
1938  if (m_copyIsTerminal[v] || closestTerminals[v].size() < 2) {
1939  continue;
1940  }
1941 
1942  std::pair<node, T> closestTerminalPair1 = *(closestTerminals[v].get(0)), closestTerminalPair2 = *(closestTerminals[v].get(1));
1943  T distanceToClosestTerminal1 = closestTerminalPair1.second, distanceToClosestTerminal2 = closestTerminalPair2.second;
1944 
1945  lowerBoundWithNode[v] = max(lowerBoundWithNode[v], minimumSpanningTreeCost - longestEdgeCost + distanceToClosestTerminal1 + distanceToClosestTerminal2);
1946  }
1947 
1948  return deleteNodesAboveUpperBound(lowerBoundWithNode, computeMinSteinerTreeUpperBound());
1949 }
1950 
1951 template<typename T>
1952 bool SteinerTreePreprocessing<T>::deleteEdgesAboveUpperBound(const EdgeArray<T> &lowerBoundWithEdge, const T upperBound)
1953 {
1954  bool changed = false;
1955  for (edge e = m_copyGraph.firstEdge(), nextE; e; e = nextE) {
1956  nextE = e->succ();
1957  if (m_eps.greater(lowerBoundWithEdge[e], upperBound)) {
1958  m_copyGraph.delEdge(e);
1959  changed = true;
1960  }
1961  }
1962  return changed;
1963 }
1964 
1965 template<typename T>
1967 {
1968  NodeArray<T> terminalRadius;
1969  computeRadiusOfTerminals(terminalRadius);
1970 
1971  // instead of sorting, we can simply ignore the two largest radii
1972  T radiusSum = T();
1973  T largestRadius1 = numeric_limits<T>::lowest(), largestRadius2 = numeric_limits<T>::lowest();
1974  for (node terminal : m_copyTerminals) {
1975  radiusSum += terminalRadius[terminal];
1976 
1977  if (terminalRadius[terminal] > largestRadius1) {
1978  largestRadius2 = largestRadius1;
1979  largestRadius1 = terminalRadius[terminal];
1980  } else {
1981  if (terminalRadius[terminal] > largestRadius2) {
1982  largestRadius2 = terminalRadius[terminal];
1983  }
1984  }
1985  }
1986  radiusSum -= largestRadius1 + largestRadius2;
1987  return radiusSum;
1988 }
1989 
1990 template<typename T>
1992 {
1994 
1995  EdgeArray<T> lowerBoundWithEdge(m_copyGraph, 0);
1996  NodeArray<List<std::pair<node, T>>> closestTerminals;
1997  computeClosestKTerminals(3, closestTerminals);
1998 
1999  const T radiusSum = computeRadiusSum();
2000 
2001  for (edge e : m_copyGraph.edges) {
2002  node x = e->source(), y = e->target();
2003 
2004  T distanceToClosestTerminalX = (*closestTerminals[x].begin()).second;
2005  T distanceToClosestTerminalY = (*closestTerminals[y].begin()).second;
2006 
2007  lowerBoundWithEdge[e] = max(lowerBoundWithEdge[e], m_copyGraph.weight(e) + distanceToClosestTerminalX + distanceToClosestTerminalY + radiusSum);
2008  }
2009 
2010  return deleteEdgesAboveUpperBound(lowerBoundWithEdge, computeMinSteinerTreeUpperBound());
2011 }
2012 
2013 template<typename T>
2014 bool SteinerTreePreprocessing<T>::reachabilityTest(int maxDegreeTest, const int k)
2015 {
2016  bool changed = false;
2019  if (maxDegreeTest <= 0) {
2020  maxDegreeTest = m_copyGraph.numberOfNodes();
2021  }
2022 
2023  EdgeWeightedGraphCopy<T> *approximatedSteinerTree;
2024  T upperBoundCost = computeMinSteinerTreeUpperBound(approximatedSteinerTree);
2025 
2026  NodeArray<bool> isInUpperBoundTree(m_copyGraph, false);
2027  for (node v : approximatedSteinerTree->nodes) {
2028  isInUpperBoundTree[approximatedSteinerTree->original(v)] = true;
2029  }
2030  delete approximatedSteinerTree;
2031 
2032  // Initialize tprime and its hpd decomposition used for partially not adding useless edges during nodes' deletion
2034 
2035  NodeArray<List<std::pair<node,T>>> closestTerminals;
2036  computeClosestKTerminals(k, closestTerminals);
2037 
2038  HeavyPathDecomposition tprimeHPD(*tprime);
2039 
2040  // check which nodes can be deleted
2041  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
2042  nextV = v->succ();
2043 
2044  if (isInUpperBoundTree[v]
2045  || v->degree() > maxDegreeTest) {
2046  continue;
2047  }
2048 
2049  // compute v's farthest and closest terminals
2050  Dijkstra<T> dijkstra;
2051 
2052  NodeArray<T> distance(m_copyGraph);
2053  NodeArray<edge> predecessor(m_copyGraph, nullptr);
2054  dijkstra.call(m_copyGraph, m_copyGraph.edgeWeights(), v, predecessor, distance);
2055 
2056  // compute first, second nearest terminals and farthest terminal
2057  node farthestTerminal = nullptr;
2058  T distanceToFarthestTerminal(0);
2059  T distanceToClosestTerminal1 = numeric_limits<T>::max(),
2060  distanceToClosestTerminal2 = numeric_limits<T>::max();
2061  for (node terminal : m_copyTerminals) {
2062  if (distanceToFarthestTerminal < distance[terminal]) {
2063  farthestTerminal = terminal;
2064  distanceToFarthestTerminal = distance[terminal];
2065  }
2066 
2067  if (distanceToClosestTerminal1 > distance[terminal]) {
2068  distanceToClosestTerminal2 = distanceToClosestTerminal1;
2069  distanceToClosestTerminal1 = distance[terminal];
2070  } else {
2071  if (distanceToClosestTerminal2 > distance[terminal]) {
2072  distanceToClosestTerminal2 = distance[terminal];
2073  }
2074  }
2075  }
2076 
2077  if (predecessor[farthestTerminal] == nullptr // is not in the same component with the terminals
2078  || distanceToClosestTerminal2 == numeric_limits<T>::max() // cannot reach at least 2 terminals, must be deleted
2079  || m_eps.geq(distanceToFarthestTerminal + distanceToClosestTerminal1 + distanceToClosestTerminal2, upperBoundCost)) {
2080  changed = true;
2081  // delete the node
2082  if (predecessor[farthestTerminal] != nullptr
2083  && distanceToClosestTerminal2 != numeric_limits<T>::max()
2084  && m_eps.less(distanceToFarthestTerminal + distanceToClosestTerminal1, upperBoundCost)) {
2085  // the deleted node has degree 2 -> replace it with edges
2086  deleteSteinerDegreeTwoNode(v, *tprime, tprimeHPD, closestTerminals);
2087  } else {
2088  // just delete the node
2089  m_copyGraph.delNode(v);
2090  }
2091  }
2092  }
2093 
2094  delete tprime;
2095 
2096  return changed;
2097 }
2098 
2099 template<typename T>
2100 template<typename LAMBDA>
2101 void SteinerTreePreprocessing<T>::computeOptimalTerminals(node v, LAMBDA dist, node &optimalTerminal1, node &optimalTerminal2, NodeArray<T> &distance) const
2102 {
2103  // run Dijkstra starting from v
2104  Dijkstra<T> dijkstra;
2105 
2106  distance.init(m_copyGraph);
2107  NodeArray<edge> predecessor(m_copyGraph, nullptr);
2108  dijkstra.call(m_copyGraph, m_copyGraph.edgeWeights(), v, predecessor, distance);
2109 
2110  for (node terminal : m_copyTerminals) {
2111  if (predecessor[terminal] == nullptr) {
2112  continue;
2113  }
2114 
2115  if (optimalTerminal1 == nullptr
2116  || dist(optimalTerminal1, distance) > dist(terminal, distance)) {
2117  optimalTerminal2 = optimalTerminal1;
2118  optimalTerminal1 = terminal;
2119  } else {
2120  if (optimalTerminal2 == nullptr
2121  || dist(optimalTerminal2, distance) > dist(terminal, distance)) {
2122  optimalTerminal2 = terminal;
2123  }
2124  }
2125  }
2126  OGDF_ASSERT(optimalTerminal1 != nullptr);
2127  OGDF_ASSERT(optimalTerminal2 != nullptr);
2128  OGDF_ASSERT(optimalTerminal1 != optimalTerminal2);
2129 }
2130 
2131 template<typename T>
2133 {
2134  if (m_copyTerminals.size() <= 2) {
2135  return false;
2136  }
2137 
2138  // get the upper bound
2139  EdgeWeightedGraphCopy<T> *approximatedSteinerTree;
2140  const T upperBoundCost = computeMinSteinerTreeUpperBound(approximatedSteinerTree);
2141 
2142  NodeArray<bool> isInUpperBoundTree(m_copyGraph, false);
2143  for (node v : approximatedSteinerTree->nodes) {
2144  isInUpperBoundTree[approximatedSteinerTree->original(v)] = true;
2145  }
2146  delete approximatedSteinerTree;
2147 
2148  T cK = T();
2149  NodeArray<T> minCostOfAdjacentEdge(m_copyGraph, numeric_limits<T>::max());
2150  for (node terminal : m_copyTerminals) {
2151  for (adjEntry adj : terminal->adjEntries) {
2152  minCostOfAdjacentEdge[terminal] = min(minCostOfAdjacentEdge[terminal], m_copyGraph.weight(adj->theEdge()));
2153  }
2154  cK += minCostOfAdjacentEdge[terminal];
2155  }
2156  auto dist = [&minCostOfAdjacentEdge](node terminal, const NodeArray<T> &distance) {
2157  return distance[terminal] - minCostOfAdjacentEdge[terminal];
2158  };
2159 
2160  List<node> delNodes;
2161  std::set<edge> delEdges;
2162  NodeArray<T> vDistance;
2163  NodeArray<T> wDistance;
2164  for (node v = m_copyGraph.firstNode(), nextV; v; v = nextV) {
2165  nextV = v->succ();
2166 
2167  if (isInUpperBoundTree[v]) {
2168  continue;
2169  }
2170 
2171  // compute its optimal terminals
2172  node vOptimalTerminal1 = nullptr, vOptimalTerminal2 = nullptr;
2173  computeOptimalTerminals(v, dist, vOptimalTerminal1, vOptimalTerminal2, vDistance);
2174 
2175  // check whether it can be deleted
2176  if (m_eps.geq(cK + dist(vOptimalTerminal1, vDistance) + dist(vOptimalTerminal2, vDistance), upperBoundCost)) {
2177  delNodes.pushBack(v);
2178  } else { // it is not deleted, perform the edge test
2179  for (adjEntry adj = v->firstAdj(), adjNext; adj; adj = adjNext) {
2180  adjNext = adj->succ();
2181  node w = adj->twinNode();
2182  if (m_copyIsTerminal[w]) {
2183  continue;
2184  }
2185  node wOptimalTerminal1 = nullptr, wOptimalTerminal2 = nullptr;
2186  computeOptimalTerminals(w, dist, wOptimalTerminal1, wOptimalTerminal2, wDistance);
2187 
2188  node vOptimalTerminal = vOptimalTerminal1;
2189  node wOptimalTerminal = wOptimalTerminal1;
2190  if (vOptimalTerminal == wOptimalTerminal) {
2191  // the nearest terminals to v and w are the same, but they have to be
2192  // different. Obtain the minimum choice such that they are different.
2193  if (m_eps.leq(
2194  dist(vOptimalTerminal1, vDistance) + dist(wOptimalTerminal2, wDistance),
2195  dist(vOptimalTerminal2, vDistance) + dist(wOptimalTerminal1, wDistance))) {
2196  wOptimalTerminal = wOptimalTerminal2;
2197  } else {
2198  vOptimalTerminal = vOptimalTerminal2;
2199  }
2200  }
2201  OGDF_ASSERT(vOptimalTerminal != wOptimalTerminal);
2202  if (m_eps.geq(cK + dist(vOptimalTerminal, vDistance) + dist(wOptimalTerminal, wDistance) + m_copyGraph.weight(adj->theEdge()), upperBoundCost)) {
2203  delEdges.insert(adj->theEdge());
2204  }
2205  }
2206  }
2207  }
2208 
2209  bool changed = false;
2210  for (edge e : delEdges) {
2211  m_copyGraph.delEdge(e);
2212  changed = true;
2213  }
2214  for (node v : delNodes) {
2215  m_copyGraph.delNode(v);
2216  changed = true;
2217  }
2218  return changed;
2219 }
2220 
2221 } // ends namespace ogdf
node target() const
Returns the target node of the edge.
Definition: Graph_d.h:327
node lowestCommonAncestor(node x, node y) const
computes the lowest common ancestor of nodes x and y using the hpd
std::vector< std::vector< node > > chainsOfTerminals
list of chains only of terminals corresponding to the decomposition
void findClosestNonTerminals(node source, List< node > &reachedNodes, NodeArray< T > &distance, T maxDistance, int expandedEdges) const
Heuristic approach to computing the closest non-terminals for one node, such that there is no termina...
std::vector< std::vector< node > > chains
list of chains of nodes corresponding to the decomposition
The parameterized class Array implements dynamic arrays of type E.
Definition: Array.h:56
bool lowerBoundBasedNodeTest()
Computes for each non-terminal a lower bound of the cost of the minimum Steiner tree containing it...
edge theEdge() const
Returns the edge associated with this adjacency entry.
Definition: Graph_d.h:95
std::enable_if< std::is_integral< T >::value, bool >::type leq(const T &x, const T &y) const
Compare if x is LEQ than y for integral types.
Definition: EpsilonTest.h:85
bool deleteNodesAboveUpperBound(const NodeArray< T > &lowerBoundWithNode, const T upperBound)
Deletes the nodes whose lowerBoundWithNode exceeds upperBound.
node copy(node v) const
Returns the node in the graph copy corresponding to v.
Definition: GraphCopy.h:336
Dijkstra&#39;s single source shortest path algorithm.
Definition: Dijkstra.h:52
node newNode(node vOrig)
Creates a new node in the graph copy with original node vOrig.
Definition: GraphCopy.h:413
SteinerTreePreprocessing(const EdgeWeightedGraph< T > &wg, const List< node > &terminals, const NodeArray< bool > &isTerminal)
An implementation of the HeavyPathDecomposition on trees.
void init()
Reinitializes the array. Associates the array with no graph.
Definition: EdgeArray.h:320
iterator pushBack(const E &x)
Adds element x at the end of the list.
Definition: List.h:1316
Data type for general directed graphs (adjacency list representation).
Definition: Graph_d.h:472
void markSuccessors(node currentNode, const Voronoi< T > &voronoiRegions, NodeArray< bool > &isSuccessorOfMinCostEdge) const
Mark successors.
void init()
Reinitializes the array. Associates the array with no graph.
Definition: NodeArray.h:292
T computeMinST(const Graph &G, const EdgeArray< T > &weight, EdgeArray< bool > &isInTree)
Computes a minimum spanning tree using Prim&#39;s algorithm.
bool leastCostTest()
Performs a least cost test [DV89] computing the whole shortest path matrix.
void dfsHeavyPathDecomposition(node v, node closestSteinerUpNode)
performs the heavy path decomposition on the tree belonging to the class updates the fields of the cl...
virtual T call(const EdgeWeightedGraph< T > &G, const List< node > &terminals, const NodeArray< bool > &isTerminal, EdgeWeightedGraphCopy< T > *&finalSteinerTree)
Builds a minimum Steiner tree given a weighted graph and a list of terminals.
This class serves as an interface for various methods to compute minimum or approximations of minimum...
int degree() const
Returns the degree of the node (indegree + outdegree).
Definition: Graph_d.h:208
void call(const Graph &G, const EdgeArray< T > &weight, const List< node > &sources, NodeArray< edge > &predecessor, NodeArray< T > &distance, bool directed=false)
Calculates, based on the graph G with corresponding edge costs and source nodes, the shortest paths a...
Definition: Dijkstra.h:61
edge newEdge(node u, node v, T weight)
iterator begin()
Returns an iterator to the first element of the list.
Definition: List.h:332
This class implements preprocessing strategies for the Steiner tree problem.
const EdgeArray< T > & edgeWeights() const
node firstNode() const
Returns the first node in the list of all nodes.
Definition: Graph_d.h:598
void computeClosestKTerminals(const int k, NodeArray< List< std::pair< node, T >>> &closestTerminals) const
Computes for every non-terminal the closest k terminals such that there is no other terminal on the p...
Implementation of Mehlhorn&#39;s minimum Steiner tree 2(1-1/l)-approximation algorithm.
Implementation of the 2(1-1/l)-approximation algorithm for the minimum Steiner tree problem by Matsuy...
void makeSimple(Graph &G)
Removes all self-loops and all but one edge of each bundle of parallel edges.
NodeArray< node > closestSteinerAncestor
the highest-level Steiner ancestor of the current node
void addNewEdge(edge e, const std::vector< node > &replacedNodes, const std::vector< edge > &replacedEdges, bool deleteReplacedElements)
The function is called after a new edge is added to the copy graph during the reductions.
bool deleteLeaves()
Deletes the leaves of the graph.
List< node > m_copyTerminals
The reduced form of terminals.
bool valid() const
Is the current subset valid? If not, all subsets have already been enumerated.
A class used by the unordered_maps inside the reductions.
T makeMinimumSpanningTree(Graph &G, const EdgeArray< T > &weight)
Reduce a graph to its minimum spanning tree (MST) using Kruskal&#39;s algorithm.
void addNewNode(node v, const std::vector< node > &replacedNodes, const std::vector< edge > &replacedEdges, bool deleteReplacedElements)
Calls addNew() for a node.
node succ() const
Returns the successor in the list of all nodes.
Definition: Graph_d.h:216
void computeOptimalTerminals(node v, LAMBDA dist, node &optimalTerminal1, node &optimalTerminal2, NodeArray< T > &distance) const
Compute first and second best terminals according to function dist.
Defines a queue for handling prioritized elements.
Prioritized queue interface wrapper for heaps.
Compare floating point numbers with epsilons and integral numbers with normal compare operators...
std::unique_ptr< MinSteinerTreeModule< T > > m_costUpperBoundAlgorithm
Algorithm used for computing the upper bound for the cost of a minimum Steiner tree.
void popBack()
Removes the last element from the list.
Definition: List.h:1367
ListIteratorBase< E, isConst > succ() const
Returns successor iterator.
Definition: List.h:133
bool nearestVertexTest()
Nearest vertex test using Voronoi regions [DV89, PV01].
bool longEdgesTest()
Long-Edges test from [DV89].
bool lowerBoundBasedEdgeTest()
Computes for each edge a lower bound of the cost of the minimum Steiner tree containing it...
std::enable_if< std::is_integral< T >::value, bool >::type less(const T &x, const T &y) const
Compare if x is LESS than y for integral types.
Definition: EpsilonTest.h:57
NodeArray< int > m_nodeSonsListIndex
It contains for each node an index i.
void del(iterator it)
Removes it from the list.
Definition: List.h:1380
T weight(const edge e) const
const List< node > & getReducedTerminals() const
Returns the list of the terminals corresponding to the reduced graph.
NodeArray< int > chainOfNode
the index of a node&#39;s chain
node binarySearchUpmostTerminal(node v, const std::vector< node > &chainOfTerminals) const
performs a binary search on chainOfTerminals, searches for the closest node to the root on chainOfTer...
const List< node > & m_origTerminals
Const reference to the original list of terminals.
edge newEdge(node v, node w, T weight)
bool reduceFast()
Apply fast reductions iteratively (includes trivial reductions).
void append(const E &x)
Adds x at the end of queue.
Definition: BoundedQueue.h:179
void createEmpty(const Graph &wG)
T computeMinSteinerTreeUpperBound(EdgeWeightedGraphCopy< T > *&finalSteinerTree) const
internal::GraphObjectContainer< EdgeElement > edges
The container containing all edge objects.
Definition: Graph_d.h:548
const NodeArray< bool > & getReducedIsTerminal() const
Returns the NodeArray<bool> isTerminal corresponding to the reduced graph.
int numberOfEdges() const
Returns the number of edges in the graph.
Definition: Graph_d.h:581
Computes Voronoi regions in an edge weighted graph.
Definition: Voronoi.h:45
const E & topElement() const
Returns the topmost element in the queue.
A class used by the unordered_maps inside the reductions.
iterator pushFront(const E &x)
Adds element x at the beginning of the list.
Definition: List.h:1303
void deleteSteinerDegreeTwoNode(node v, const EdgeWeightedGraphCopy< T > &tprime, const HeavyPathDecomposition &tprimeHPD, const NodeArray< List< std::pair< node, T >>> &closestTerminals)
Deletes a node that is known to have degree 2 in at least one minimum Steiner tree.
EdgeWeightedGraph< T > m_copyGraph
Copy of the original graph; this copy will actually be reduced.
void begin(int low, int high)
Initialize the SubsetEnumerator to enumerate subsets of cardinalities from low to high...
void addToSolution(const int listIndex, Array< bool, int > &isInSolution) const
Helper method for computeOriginalSolution.
INDEX size() const
Returns the size (number of elements) of the array.
Definition: Array.h:134
void computeRadiusOfTerminals(NodeArray< T > &terminalRadius) const
Compute radius of terminals.
const EdgeArray< T > & edgeWeights() const
bool terminalDistanceTest()
Simple terminal distance test [PV01].
void computeLongestDistToSteinerAncestorSegTree()
creates for every chain a segment tree built on a fictive array which keeps for every node the sum of...
std::vector< node > fatherOfChain
the first node from bottom up that does not belong to the chain
bool shortLinksTest()
Short links test using Voronoi regions [PV01].
Enumerator for k-subsets of a given type.
Doubly linked lists (maintaining the length of the list).
Definition: List.h:39
edge newEdge(node v, node w)
Creates a new edge (v,w) and returns it.
node seed(node v) const
Returns the Voronoi seed of node v.
Definition: Voronoi.h:86
T m_costAlreadyInserted
The cost of the already inserted in solution edges.
bool addEdgesToSolution(const List< edge > &edgesToBeAddedInSolution)
The function adds a set of edges in the solution.
bool PTmTest(const int k=3)
"Paths with many terminals" test, efficient on paths with many terminals.
void buildMaxSegmentTree(std::vector< T > &segmentTree, const int nodeIndex, const int left, const int right, const std::vector< T > &baseArray) const
builds a max segment tree on the baseArray
bool isLoopFree(const Graph &G)
Returns true iff G contains no self-loop.
bool NTDkTest(const int maxTestedDegree=5, const int k=3)
Non-terminals of degree k test [DV89, PV01].
node twinNode() const
Returns the associated node of the corresponding adjacency entry (shorthand for twin()->theNode()).
Definition: Graph_d.h:105
Class for the representation of edges.
Definition: Graph_d.h:291
NodeArray< int > positionOnChain
position of a node on his chain
bool reduceTrivial()
Apply trivial (hence amazingly fast) reductions iteratively, that is degree2Test(), makeSimple(), deleteLeaves().
NodeArray< int > weightOfSubtree
weight of the subtree rooted in one node
const EdgeWeightedGraphCopy< T > & tree
constant ref to the tree to be decomposed
T computeRadiusSum() const
Compute the sum of all radii except the two largest.
T distance(node v) const
Returns the distance between v and its Voronoi seed.
Definition: Voronoi.h:80
adjEntry lastAdj() const
Returns the last entry in the adjacency list.
Definition: Graph_d.h:213
Class for the representation of nodes.
Definition: Graph_d.h:167
void computeOriginalSolution(const EdgeWeightedGraphCopy< T > &reducedGraphSolution, EdgeWeightedGraphCopy< T > &correspondingOriginalSolution)
Computes the solution for the original graph, given a solution on the reduction.
Priority queue interface wrapping various heaps.
Encapsulates a pointer to a list element.
Definition: List.h:41
std::enable_if< std::is_integral< T >::value, bool >::type greater(const T &x, const T &y) const
Compare if x is GREATER than y for integral types.
Definition: EpsilonTest.h:169
bool reachabilityTest(int maxDegreeTest=0, const int k=3)
Performs a reachability test [DV89].
node opposite(node v) const
Returns the adjacent node different from v.
Definition: Graph_d.h:335
const NodeArray< bool > & m_origIsTerminal
Const reference to the original isTerminal.
NodeArray< T > distanceToRoot
the length of the edge to his father
void addNew(TWhat x, const std::vector< node > &replacedNodes, const std::vector< edge > &replacedEdges, bool deleteReplacedElements, TWhatArray &whatSonsListIndex)
Update internal data structures to let a (new) node or edge represent replaced nodes and/or edges...
const Graph & original() const
Returns a reference to the original graph.
Definition: GraphCopy.h:287
bool degree2Test()
deletes degree-2 nodes and replaces them with one edge with the adjacent edges&#39; sum ...
void floydWarshall(NodeArray< NodeArray< T >> &shortestPath) const
Applies the Floyd-Warshall algorithm on the m_copyGraph. The shortestPath matrix has to be already in...
This class implements the minimum Steiner tree 2-approximation algorithm by Takahashi and Matsuyama w...
NodeArray< bool > m_copyIsTerminal
The reduced form of isTerminal.
const EdgeWeightedGraph< T > & m_origGraph
Const reference to the original graph.
std::vector< std::vector< int > > m_sonsList
List with lists (corresponding to nodes and containing the indexes of their sons) ...
std::vector< std::vector< T > > longestDistToSteinerAncestorSegTree
segment tree for segment maxs on every chain
int index() const
Returns the (unique) node index.
Definition: Graph_d.h:201
EdgeArray< int > m_edgeSonsListIndex
See m_nodeSonsListIndex but for edges.
edge succ() const
Returns the successor in the list of all edges.
Definition: Graph_d.h:340
bool empty() const
Checks whether the queue is empty.
List< node > terminals
list of terminals of the desc tree
T getBottleneckSteinerDistance(node x, node y) const
computes in the bottleneck distance between terminals x and y
const NodeArray< bool > isTerminal
isTerminal of the desc tree
bool deleteComponentsWithoutTerminals()
Deletes connected components with no terminals.
void next()
Obtain the next subset if possible. The result should be checked using the valid() method...
adjEntry succ() const
Returns the successor in the adjacency list.
Definition: Graph_d.h:145
int size() const
Returns the number of elements in the list.
Definition: List.h:1255
void computeBottleneckOnBranch(node x, node ancestor, T &longestPathDistance, T &fromLowestToAncestor) const
computes for the path from x to ancestor the maximum distance (sum of edges) between any two consecut...
bool makeSimple()
Deletes parallel edges keeping only the minimum cost one, and deletes self-loops. ...
iterator begin()
Returns an iterator to the first entry in the node array.
Definition: NodeArray.h:215
int maxNodeIndex() const
Returns the largest used node index.
Definition: Graph_d.h:584
HeavyPathDecomposition(const EdgeWeightedGraphCopy< T > &treeEWGraphCopy)
void recomputeTerminalsList()
Used by reductions to recompute the m_copyTerminals list, according to m_copyIsTerminal; useful when ...
EdgeWeightedGraphCopy< T > * initializeTPrime() const
node predecessor(node v) const
Returns the nearest node to v on the shortest path to its Voronoi seed.
Definition: Voronoi.h:73
node source() const
Returns the source node of the edge.
Definition: Graph_d.h:325
T solve(MinSteinerTreeModule< T > &mst, EdgeWeightedGraphCopy< T > *&finalSteinerTree)
A shortcut to get the solution of a reduced instance.
bool cutReachabilityTest()
Performs a cut reachability test [DV89].
bool isSimple(const Graph &G)
Returns true iff G contains neither self-loops nor parallel edges.
int size() const
Return the cardinality of the subset.
NodeArray< int > nodeLevel
the level of a node in the tree
The namespace for all OGDF objects.
Implementation of Voronoi regions in an EdgeWeightedGraph.
Declaration and implementation of bounded queue class.
T getMaxSegmentTree(const std::vector< T > &segmentTree, const int nodeIndex, const int left, const int right, const int queryLeft, const int queryRight) const
extracts the maximum on the required interval
int maxEdgeIndex() const
Returns the largest used edge index.
Definition: Graph_d.h:586
std::enable_if< std::is_integral< T >::value, bool >::type geq(const T &x, const T &y) const
Compare if x is GEQ to y for integral types.
Definition: EpsilonTest.h:141
static void calculateCompleteGraph(const EdgeWeightedGraph< T > &wG, const List< node > &terminals, const Voronoi< T > &voronoi, EdgeArray< edge > &bridges, EdgeWeightedGraphCopy< T > &completeTerminalGraph)
Builds a complete terminal graph.
bool deleteEdgesAboveUpperBound(const EdgeArray< T > &lowerBoundWithEdge, const T upperBound)
Deletes the edges whose lowerBoundWithEdge exceeds upperBound.
int numberOfNodes() const
Returns the number of nodes in the graph.
Definition: Graph_d.h:578
Handle push(const E &element, const P &priority)
Pushes a new element with the respective priotiy to the queue.
node newNode()
Creates a new node and returns it.
internal::GraphObjectContainer< NodeElement > nodes
The container containing all node objects.
Definition: Graph_d.h:545
adjEntry firstAdj() const
Returns the first entry in the adjaceny list.
Definition: Graph_d.h:211
bool isConnected(const Graph &G)
Returns true iff G is connected.
int connectedComponents(const Graph &G, NodeArray< int > &component)
Computes the connected components of G.
void computeShortestPathMatrix(NodeArray< NodeArray< T >> &shortestPath) const
Computes the shortest path matrix corresponding to the m_copyGraph.
A class that allows to enumerate k-subsets of lists.
bool empty() const
Returns true iff the list is empty.
Definition: List.h:236
bool repeat(Fun f) const
Repeat a function until it returns false (used for iteratively applying reductions) ...
The parameterized class BoundedQueue implements queues with bounded size.
Definition: BoundedQueue.h:46
T distanceToAncestor(node v, node ancestor) const
computes the sum of all edges on the path from v to ancestor v must be in ancestor&#39;s subtree ...
Class for adjacency list elements.
Definition: Graph_d.h:78
void computeLongestDistToSteinerAncestorOnChain()
creates for every chain an array with the maximum of every prefix of a fictive array which keeps for ...
std::vector< std::vector< T > > longestDistToSteinerAncestorOnChain
the max of the interval 0..i for every i on chains
#define OGDF_ASSERT(expr)
Assert condition expr. See doc/build.md for more information.
Definition: basic.h:41
T computeBottleneckDistance(node x, node y, const EdgeWeightedGraphCopy< T > &tprime, const HeavyPathDecomposition &tprimeHPD, const NodeArray< List< std::pair< node, T >>> &closestTerminals) const
Heuristic computation [PV01] of the bottleneck Steiner distance between two nodes in a graph...
internal::GraphObjectContainer< AdjElement > adjEntries
The container containing all entries in the adjacency list of this node.
Definition: Graph_d.h:198