Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Johnson.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
74#ifndef JOHNSON_H
75#define JOHNSON_H
76
77# include <ah-graph-concepts.H>
78
79#include <Dijkstra.H>
80#include <Bellman_Ford.H>
81#include <tpl_graph.H>
82#include <tpl_dynList.H>
83#include <tpl_dynMapTree.H>
84#include <ah-errors.H>
85#include <algorithm>
86#include <concepts>
87#include <cstdint>
88#include <limits>
89#include <stdexcept>
90#include <type_traits>
91#include <utility>
92#include <vector>
93
94namespace Aleph
95{
96
97namespace johnson_detail
98{
107struct Wide
108{
109 std::uint64_t hi = 0;
110 std::uint64_t lo = 0;
111
113 template <std::integral T>
114 [[nodiscard]] static constexpr Wide of(const T x) noexcept
115 {
116 if constexpr (std::is_signed_v<T>)
117 return Wide{x < 0 ? ~std::uint64_t(0) : std::uint64_t(0),
118 static_cast<std::uint64_t>(static_cast<std::int64_t>(x))};
119 else
120 return Wide{0, static_cast<std::uint64_t>(x)};
121 }
122
124 [[nodiscard]] friend constexpr Wide operator + (const Wide & a, const Wide & b) noexcept
125 {
126 const std::uint64_t lo = a.lo + b.lo;
127 return Wide{a.hi + b.hi + (lo < a.lo ? 1 : 0), lo};
128 }
129
131 [[nodiscard]] friend constexpr Wide operator - (const Wide & a, const Wide & b) noexcept
132 {
133 return Wide{a.hi - b.hi - (a.lo < b.lo ? 1 : 0), a.lo - b.lo};
134 }
135
137 [[nodiscard]] friend constexpr bool operator == (const Wide & a, const Wide & b) noexcept
138 = default;
139
141 [[nodiscard]] friend constexpr bool operator < (const Wide & a, const Wide & b) noexcept
142 {
143 return a.hi < b.hi or (a.hi == b.hi and a.lo < b.lo);
144 }
145
147 [[nodiscard]] static constexpr bool signed_less(const Wide & a, const Wide & b) noexcept
148 {
149 constexpr std::uint64_t sign = std::uint64_t(1) << 63;
150 return Wide{a.hi ^ sign, a.lo} < Wide{b.hi ^ sign, b.lo};
151 }
152};
153} // namespace johnson_detail
154
210template <AlephGraph GT,
211 ArcDistance<GT> Distance = Dft_Dist<GT>,
212 template <class, class> class Ait = Arc_Iterator,
213 template <class, class> class NAit = Node_Arc_Iterator,
214 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
216{
217public:
218 using Node = typename GT::Node;
219 using Arc = typename GT::Arc;
221
222private:
223 // An integer type, other than bool, keeps the new weights and their sums
224 // in its unsigned type
225 static constexpr bool Integer = std::is_integral_v<Distance_Type>
226 and not std::is_same_v<std::remove_cv_t<Distance_Type>, bool>;
227
228 // The type of the new weights w + h(u) - h(v) and of their sums: for an
229 // integer type, the unsigned one of the same width, where they fit
230 // whenever the distances fit; else the type of the distances
231 using Weight =
232 typename std::conditional_t<Integer,
233 std::make_unsigned<std::remove_cv_t<Distance_Type>>,
234 std::type_identity<Distance_Type>>::type;
235
236 // A signed integer type of up to 64 bits may have a potential below
237 // lowest(): then the potentials, the new weights and the sums of
238 // Dijkstra are kept in an integer of 128 bits, where they fit
239 static constexpr bool Signed_Integer = Integer and std::is_signed_v<Distance_Type>
240 and sizeof(Distance_Type) <= sizeof(std::int64_t);
241
243
244 static constexpr size_t None = std::numeric_limits<size_t>::max();
245
246 // A way in which an arc that the filter shows is taken: from the node
247 // number u to the node number v, with the weight w; copy is the copy of
248 // the arc, or nullptr for the second way of an arc of a graph that is
249 // not directed
251 {
252 size_t u;
253 size_t v;
257 };
258
259 // The digraph on which Bellman-Ford computes the potentials: a node for
260 // each one of the graph, with its number, and an arc for each Shown_Arc,
261 // with its weight
263
264 const GT* orig_graph = nullptr;
267 std::vector<Node*> nodes;
268 std::vector<Node*> copies;
269 std::vector<Distance_Type> h;
270
271 // The arcs on which Dijkstra runs. Those out of the node number u are
272 // the e from out_first[u] to out_first[u + 1] - 1: to the node number
273 // out_target[e], of new weight out_weight[e], ways of the arc out_arc[e]
274 // of the graph. A loop shortens no path: it is not there.
275 std::vector<size_t> out_first;
276 std::vector<size_t> out_target;
277 std::vector<Weight> out_weight;
278 std::vector<Arc*> out_arc;
279
280 // Whether the solver has a graph, and the type of its potentials: that
281 // of the distances, or, when one is below lowest(), 128 bits (wide_h). A
282 // query checks it once, as it checked whether the solver had a graph.
283 enum Mode : unsigned char
284 {
288 };
290
291 // What Dijkstra knows of a node
292 enum : unsigned char
293 {
294 Unreached = 0, // no path from the source
295 Labeled, // a path from the source, maybe not a shortest one
296 Settled, // its distance from the source
297 Too_Far, // the sums of its paths leave the range of Weight
298 Settled_Wide // as Settled, on the wide weights
299 };
300
301 // The tree of the shortest paths from the last source from which a
302 // query ran Dijkstra: for each node, what Dijkstra knows of it, its
303 // distance on the new weights, and the node and the arc (an index of the
304 // arcs of Dijkstra) before it
305 std::vector<unsigned char> state;
306 std::vector<Weight> reach;
307 std::vector<size_t> parent;
308 std::vector<size_t> via;
309
310 // The heap of Dijkstra, of pairs (distance, node), with room for each
311 // pair that it may get: one for the source and one for each arc. A node
312 // may have several pairs in it: the first one out is that of its
313 // distance, and the others are left aside.
314 std::vector<std::pair<Weight, size_t>> heap;
315
316 // With the mode Wide_Potentials, the potentials, the new weights, the
317 // distances of Dijkstra on them and its heap are these, in an integer of
318 // 128 bits, instead of out_weight, reach and heap, which are left empty;
319 // h keeps the potentials that fit, and 1, which no potential is, for
320 // those below lowest()
321 std::vector<Wide> wide_h;
322 std::vector<Wide> wide_weight;
323 std::vector<Wide> wide_reach;
324 std::vector<std::pair<Wide, size_t>> wide_heap;
325
326 // The new weights, the distances of Dijkstra and its heap: the wide ones
327 // if W
328 template <bool W>
329 auto & weights_of() noexcept
330 {
331 if constexpr (W)
332 return wide_weight;
333 else
334 return out_weight;
335 }
336
337 template <bool W>
338 auto & reach_of() noexcept
339 {
340 if constexpr (W)
341 return wide_reach;
342 else
343 return reach;
344 }
345
346 template <bool W>
347 auto & heap_of() noexcept
348 {
349 if constexpr (W)
350 return wide_heap;
351 else
352 return heap;
353 }
354
355 // The number of the source of the tree that is kept, or None. A move of
356 // the solver gives it to the new one and leaves the old one without it.
358 {
359 size_t node = None;
360
361 Kept_Source() = default;
362
363 Kept_Source(Kept_Source && other) noexcept
364 : node(std::exchange(other.node, None))
365 {
366 // empty
367 }
368
370 {
371 node = std::exchange(other.node, None);
372 return *this;
373 }
375
376 // The number of a node of the graph
377 size_t number_of(Node * p) const
378 {
379 auto * q = number.search(p);
380 ah_domain_error_if(q == nullptr)
381 << "Node not found in mapping (not from original graph?)";
382 return q->second;
383 }
384
385 // w + hu - hv, which is >= 0 and, with an integer type, at most max() +
386 // max() + 1, as lowest() <= h <= 0: exact in Weight, modulo its range
387 static Weight reweight(const Distance_Type & w, const Distance_Type & hu,
388 const Distance_Type & hv)
389 {
390 if constexpr (Integer)
391 return Weight(Weight(Weight(w) + Weight(hu)) - Weight(hv));
392 else
393 return w + hu - hv;
394 }
395
396 // a + b in sum, or false if it leaves the range of Weight, which only an
397 // integer type has
398 static bool add(const Weight & a, const Weight & b, Weight & sum)
399 {
400 if constexpr (Integer)
401 if (b > Weight(std::numeric_limits<Weight>::max() - a))
402 return false;
403
404 sum = Weight(a + b);
405 return true;
406 }
407
408 // As add(), for unsigned integers of 128 bits
409 static bool add(const Wide & a, const Wide & b, Wide & sum)
410 {
411 sum = a + b;
412 return not (sum < a);
413 }
414
415 // The new weight of an arc, in the info of its copy, if the info can take
416 // a distance: max() if, with an integer type, it is beyond max()
417 static void write_info(Arc * copy, const Weight & w)
418 {
419 if constexpr (std::is_assignable_v<typename GT::Arc_Type &, const Distance_Type &>)
420 {
421 if constexpr (Integer)
422 {
423 constexpr Distance_Type max = std::numeric_limits<Distance_Type>::max();
424 const Distance_Type value = w > Weight(max) ? max : static_cast<Distance_Type>(w);
425 copy->get_info() = value;
426 }
427 else
428 copy->get_info() = w;
429 }
430 }
431
432 // As write_info(), for a new weight of 128 bits
433 static void write_info(Arc * copy, const Wide & w)
434 {
435 if constexpr (std::is_assignable_v<typename GT::Arc_Type &, const Distance_Type &>)
436 {
437 constexpr Distance_Type max = std::numeric_limits<Distance_Type>::max();
438 const Distance_Type value = w.hi != 0 or w.lo > static_cast<std::uint64_t>(max)
439 ? max : static_cast<Distance_Type>(w.lo);
440 copy->get_info() = value;
441 }
442 }
443
444 // The distance to a node that cannot be reached: infinity, or max() for
445 // a type that has none, as an integer type, whose infinity() is 0
446 static constexpr Distance_Type unreachable() noexcept
447 {
448 if constexpr (std::numeric_limits<Distance_Type>::has_infinity)
449 return std::numeric_limits<Distance_Type>::infinity();
450 else
451 return std::numeric_limits<Distance_Type>::max();
452 }
453
454 // The distance d(s, t) = d'(s, t) - h(s) + h(t), from d'(s, t), that of
455 // the new weights. With an integer type it is >= h(t) - h(s) >=
456 // lowest(), and above max() if d'(s, t) - h(s) > max() - h(t), whose
457 // terms are >= 0 and fit in Weight; else it is exact modulo the range of
458 // Weight
459 static Distance_Type unweighted(const Weight & d_prime, const Distance_Type & hs,
460 const Distance_Type & ht)
461 {
462 if constexpr (Integer)
463 {
464 const Weight minus_hs = Weight(Weight(0) - Weight(hs));
465 const Weight minus_ht = Weight(Weight(0) - Weight(ht));
466 const Weight room =
467 Weight(Weight(std::numeric_limits<Distance_Type>::max()) + minus_ht);
468
469 ah_overflow_error_if(minus_hs > room or d_prime > Weight(room - minus_hs))
470 << "Integer overflow: a distance is above max()";
471
472 return static_cast<Distance_Type>(Weight(Weight(d_prime + minus_hs) - minus_ht));
473 }
474 else
475 return d_prime - hs + ht;
476 }
477
478 // As unweighted(), on the wide weights: d(s, t) = d'(s, t) - h(s) +
479 // h(t), exact in 128 bits, if it fits in the type
480 static Distance_Type wide_unweighted(const Wide & d_prime, const Wide & hs, const Wide & ht)
481 {
482 const Wide d = d_prime - hs + ht;
483 ah_overflow_error_if(Wide::signed_less(Wide::of(std::numeric_limits<Distance_Type>::max()), d))
484 << "Integer overflow: a distance is above max()";
485 ah_overflow_error_if(Wide::signed_less(d, Wide::of(std::numeric_limits<Distance_Type>::lowest())))
486 << "Integer overflow: a distance is below lowest()";
487
488 return static_cast<Distance_Type>(static_cast<std::int64_t>(d.lo));
489 }
490
491 // The distance from the node number s, the source of the tree that is
492 // kept, to the node number t
493 Distance_Type distance_to(size_t s, size_t t) const
494 {
495 if (state[t] == Unreached)
496 return unreachable();
497
498 if (state[t] != Settled) [[unlikely]]
499 return distance_apart(s, t);
500
501 return unweighted(reach[t], h[s], h[t]);
502 }
503
504 // As distance_to(), for a node too far, which throws, or settled on the
505 // wide weights
506 [[gnu::noinline]] Distance_Type distance_apart(size_t s, size_t t) const
507 {
508 if constexpr (Signed_Integer)
509 if (state[t] == Settled_Wide)
510 return wide_unweighted(wide_reach[t], wide_h[s], wide_h[t]);
511
512 ah_overflow_error() << "Integer overflow: a distance is above max()";
513 }
514
515 // Gives the state Too_Far to the nodes that the nodes too far reach and
516 // Dijkstra did not, whose distances, as theirs, are beyond max(); with
517 // the heap of the wide weights if W
518 template <bool W>
520 {
521 auto & stack = heap_of<W>();
522 using Key = typename std::remove_reference_t<decltype(stack)>::value_type::first_type;
523 // Key{} is 0; Clang 14 does not take Key(0) for an aggregate
524
525 for (size_t v = 0; v < state.size(); ++v)
526 if (state[v] == Too_Far)
527 stack.emplace_back(Key{}, v);
528
529 while (not stack.empty())
530 {
531 const size_t u = stack.back().second;
532 stack.pop_back();
533 for (size_t e = out_first[u], end = out_first[u + 1]; e < end; ++e)
534 if (const size_t v = out_target[e]; state[v] == Unreached)
535 {
536 state[v] = Too_Far;
537 stack.emplace_back(Key{}, v);
538 }
539 }
540 }
541
542 // Runs Dijkstra from the node number s on the new weights, the wide ones
543 // if W, which leaves the nodes that it reaches as Settled, or
544 // Settled_Wide. A sum that leaves the range of the weights, which only
545 // an integer type has, is no path: a node that is reached only through
546 // such sums is too far, as its distance is beyond max(), and so are the
547 // nodes that only it reaches. It does not allocate.
548 template <bool W>
549 [[gnu::always_inline]] inline void paint(size_t s)
550 {
551 using Key = typename std::remove_reference_t<decltype(weights_of<W>())>::value_type;
552 constexpr unsigned char Done = W ? Settled_Wide : Settled;
553 const auto & weight = weights_of<W>();
554 auto & dist = reach_of<W>();
555 auto & pairs = heap_of<W>();
556
557 const auto later = [] (const std::pair<Key, size_t> & a,
558 const std::pair<Key, size_t> & b)
559 {
560 return b.first < a.first;
561 };
562
563 kept.node = None; // until the tree is whole
564 std::fill(state.begin(), state.end(), Unreached);
565 pairs.clear();
566 bool too_far = false;
567
568 state[s] = Labeled;
569 dist[s] = Key{};
570 parent[s] = via[s] = None;
571 pairs.emplace_back(Key{}, s);
572 while (not pairs.empty())
573 {
574 std::pop_heap(pairs.begin(), pairs.end(), later);
575 const size_t u = pairs.back().second;
576 pairs.pop_back();
577 if (state[u] == Done)
578 continue; // a pair left aside
579
580 state[u] = Done;
581 const Key du = dist[u];
582 for (size_t e = out_first[u], end = out_first[u + 1]; e < end; ++e)
583 {
584 const size_t v = out_target[e];
585 if (state[v] == Done)
586 continue;
587
588 Key dv{};
589 if (not add(du, weight[e], dv))
590 {
591 if (state[v] == Unreached)
592 {
593 state[v] = Too_Far;
594 too_far = true;
595 }
596 continue;
597 }
598
599 if (state[v] == Labeled and not (dv < dist[v]))
600 continue;
601
602 state[v] = Labeled;
603 dist[v] = dv;
604 parent[v] = u;
605 via[v] = e;
606 pairs.emplace_back(dv, v);
607 std::push_heap(pairs.begin(), pairs.end(), later);
608 }
609 }
610
611 if (too_far)
612 spread_too_far<W>();
613
614 kept.node = s;
615 }
616
617 // As paint(), on the wide weights
618 [[gnu::noinline]] void paint_wide(size_t s) { paint<true>(s); }
619
620 // Runs Dijkstra from the node number s, unless the tree that is kept is
621 // that of s
622 void paint_from(size_t s)
623 {
624 if (kept.node == s)
625 return;
626
627 if constexpr (Signed_Integer)
628 if (mode == Wide_Potentials) [[unlikely]]
629 {
630 paint_wide(s);
631 return;
632 }
633
634 paint<false>(s);
635 }
636
637public:
659 explicit Johnson(const GT& g, Distance d = Distance(), SA __sa = SA())
660 : orig_graph(&g)
661 {
662 const size_t n = g.get_num_nodes();
663 nodes.reserve(n);
664 copies.reserve(n);
665
667 std::vector<typename Potential_Graph::Node *> pnodes;
668 pnodes.reserve(n);
669 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
670 {
671 Node * p = it.get_curr_ne();
672 number.insert(p, nodes.size());
673 pnodes.push_back(pg.insert_node(nodes.size()));
674 copies.push_back(reweighted.insert_node(p->get_info()));
675 nodes.push_back(p);
676 }
677
678 // Each arc is copied; those that the filter shows are taken from their
679 // sources, and also from their targets if the graph is not directed
680 const bool directed = g.is_digraph();
681 std::vector<Shown_Arc> shown;
682 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
683 {
684 Arc * a = it.get_curr_ne();
685 const size_t u = number.find(g.get_src_node(a));
686 const size_t v = number.find(g.get_tgt_node(a));
687 Arc * copy = reweighted.insert_arc(copies[u], copies[v], a->get_info());
688 if (not __sa(a))
689 continue;
690
691 const Distance_Type w = d(a);
692 shown.push_back(Shown_Arc{u, v, w, a, copy});
693 if (not directed and u != v)
694 shown.push_back(Shown_Arc{v, u, w, a, nullptr});
695 }
696
697 // The potentials; this throws with a negative cycle. With a signed
698 // integer type, Bellman-Ford throws overflow_error when a sum goes
699 // below lowest(), as when a potential is below it, or on a negative
700 // cycle of large weights: the potentials are computed again in 128
701 // bits, which also tells the negative cycle
702 for (const Shown_Arc & x : shown)
703 pg.insert_arc(pnodes[x.u], pnodes[x.v], x.w);
704 bool wide = false;
705 if constexpr (Signed_Integer)
706 {
707 try
708 {
709 narrow_potentials(pg, pnodes);
710 }
711 catch (const std::overflow_error &)
712 {
713 h.clear();
714 wide_potentials(shown);
715 wide = true;
716 }
717 }
718 else
719 narrow_potentials(pg, pnodes);
720
721 // The arcs of Dijkstra, grouped by their sources in the order of the
722 // arcs of the graph, with their new weights, which the copies of the
723 // arcs take as infos
724 out_first.assign(n + 1, 0);
725 for (const Shown_Arc & x : shown)
726 if (x.u != x.v)
727 ++out_first[x.u + 1];
728 for (size_t i = 0; i < n; ++i)
729 out_first[i + 1] += out_first[i];
730
731 if constexpr (Signed_Integer)
732 if (wide) [[unlikely]]
733 {
734 wide_arcs(shown);
735 return;
736 }
737
738 const size_t m = out_first[n];
740 out_weight.resize(m);
741 out_arc.resize(m);
742 std::vector<size_t> next(out_first.begin(), out_first.end() - 1);
743 for (const Shown_Arc & x : shown)
744 {
745 const Weight w = reweight(x.w, h[x.u], h[x.v]);
746 if (x.copy != nullptr)
747 write_info(x.copy, w);
748 if (x.u == x.v)
749 continue;
750
751 const size_t e = next[x.u]++;
752 out_target[e] = x.v;
753 out_weight[e] = w;
754 out_arc[e] = x.arc;
755 }
756
757 state.assign(n, Unreached);
758 reach.resize(n);
759 parent.assign(n, None);
760 via.assign(n, None);
761 heap.reserve(m + 1);
762
764 }
765
766private:
767 // The potentials in h, from Bellman-Ford on pg, whose node number i is
768 // pnodes[i]. In line, as when it was in the constructor: out of line, its
769 // loop runs more instructions.
770 [[gnu::always_inline]] inline void narrow_potentials(Potential_Graph & pg,
771 const std::vector<typename Potential_Graph::Node *> & pnodes)
772 {
774 const auto potentials = bf.compute_nodes_weights();
775 h.reserve(pnodes.size());
776 for (size_t i = 0; i < pnodes.size(); ++i)
777 h.push_back(potentials.find(pnodes[i]));
778 }
779
780 // The potentials in wide_h, in 128 bits: a Bellman-Ford
781 // from a virtual source that reaches every node by an arc of weight 0,
782 // on the arcs shown. Without a negative cycle a potential is at least
783 // (n - 1) lowest(), and the pass n changes none; with one, after n
784 // passes a potential is at least n m lowest(): they fit in 128 bits.
785 void wide_potentials(const std::vector<Shown_Arc> & shown)
786 {
787 const size_t n = nodes.size();
788 wide_h.assign(n, Wide{});
789 for (size_t pass = 1; ; ++pass)
790 {
791 bool changed = false;
792 for (const Shown_Arc & x : shown)
793 if (const Wide sum = wide_h[x.u] + Wide::of(x.w);
795 {
796 wide_h[x.v] = sum;
797 changed = true;
798 }
799
800 if (not changed)
801 break;
802
803 ah_domain_error_if(pass >= n) << "negative cycles detected";
804 }
805 }
806
807 // As the end of the constructor, for the wide potentials: the arcs of
808 // Dijkstra, with their new weights in 128 bits
809 void wide_arcs(const std::vector<Shown_Arc> & shown)
810 {
811 const size_t n = nodes.size();
812 const size_t m = out_first[n];
814 wide_weight.resize(m);
815 out_arc.resize(m);
816 std::vector<size_t> next(out_first.begin(), out_first.end() - 1);
817 for (const Shown_Arc & x : shown)
818 {
819 const Wide w = Wide::of(x.w) + wide_h[x.u] - wide_h[x.v];
820 if (x.copy != nullptr)
821 write_info(x.copy, w);
822 if (x.u == x.v)
823 continue;
824
825 const size_t e = next[x.u]++;
826 out_target[e] = x.v;
827 wide_weight[e] = w;
828 out_arc[e] = x.arc;
829 }
830
831 state.assign(n, Unreached);
832 wide_reach.resize(n);
833 parent.assign(n, None);
834 via.assign(n, None);
835 wide_heap.reserve(m + 1);
836
837 h.resize(n);
838 for (size_t i = 0; i < n; ++i)
839 h[i] = Wide::signed_less(wide_h[i], Wide::of(std::numeric_limits<Distance_Type>::lowest()))
840 ? Distance_Type(1) : static_cast<Distance_Type>(static_cast<std::int64_t>(wide_h[i].lo));
841
843 }
844
845public:
846
848 Johnson() = default;
849
852 Johnson(const Johnson &) = delete;
853
856 Johnson & operator = (const Johnson &) = delete;
857
859 Johnson(Johnson &&) = default;
860
862 Johnson & operator = (Johnson &&) = default;
863
867 [[nodiscard]] bool is_initialized() const noexcept { return mode != No_Graph; }
868
886 requires std::is_convertible_v<typename GT::Arc_Type, Distance_Type>
887 {
888 ah_domain_error_if(mode == No_Graph) << "Johnson not initialized";
889 ah_domain_error_if(src == nullptr or tgt == nullptr) << "Source or target node is null";
890
891 // Same node - distance is 0
892 if (src == tgt)
893 return Distance_Type(0);
894
895 const size_t s = number_of(src);
896 const size_t t = number_of(tgt);
897
898 // Run Dijkstra from src, if its tree is not the one that is kept
899 paint_from(s);
900
901 return distance_to(s, t);
902 }
903
914 requires std::is_convertible_v<typename GT::Arc_Type, Distance_Type>
915 {
916 ah_domain_error_if(mode == No_Graph) << "Johnson not initialized";
917 ah_domain_error_if(src == nullptr or tgt == nullptr) << "Source or target node is null";
918
919 const size_t s = number_of(src);
920 const size_t t = number_of(tgt);
921
922 Path<GT> path(*orig_graph);
923 if (s == t)
924 {
925 path.init(src);
926 return path;
927 }
928
929 // Run Dijkstra from src, if its tree is not the one that is kept
930 paint_from(s);
931
932 if (state[t] == Unreached)
933 return path;
934
935 (void) distance_to(s, t); // overflow_error if it does not fit
936
937 std::vector<Arc*> arcs; // of the tree, from tgt back to src
938 for (size_t v = t; v != s; v = parent[v])
939 arcs.push_back(out_arc[via[v]]);
940
941 path.init(src);
942 for (auto it = arcs.rbegin(); it != arcs.rend(); ++it)
943 path.append(*it);
944
945 return path;
946 }
947
959 requires std::is_convertible_v<typename GT::Arc_Type, Distance_Type>
960 {
961 ah_domain_error_if(mode == No_Graph) << "Johnson not initialized";
962
964
965 // For each node as source
966 for (size_t s = 0; s < nodes.size(); ++s)
967 {
968 // Run Dijkstra from it, if its tree is not the one that is kept
969 paint_from(s);
970
971 // Get distance to all targets
972 for (size_t t = 0; t < nodes.size(); ++t)
973 result.insert(std::make_pair(nodes[s], nodes[t]), distance_to(s, t));
974 }
975
976 return result;
977 }
978
993 {
994 ah_domain_error_if(mode == No_Graph) << "Johnson not initialized";
995 const Distance_Type p = h[number_of(node)];
996 if constexpr (Signed_Integer)
997 ah_overflow_error_if(p > Distance_Type(0)) // 1, for one below lowest()
998 << "Integer overflow: a potential is below lowest()";
999 return p;
1000 }
1001
1017 GT& get_reweighted_graph() noexcept { return reweighted; }
1018
1024 const GT& get_reweighted_graph() const noexcept { return reweighted; }
1025
1032 Node* get_copy_node(Node* orig) const { return copies[number_of(orig)]; }
1033};
1034
1035} // namespace Aleph
1036
1037#endif // JOHNSON_H
Bellman-Ford algorithm for single-source shortest paths.
Dijkstra's shortest path algorithm.
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_overflow_error()
Throws std::overflow_error unconditionally.
Definition ah-errors.H:643
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
Bellman-Ford algorithm for shortest paths with negative weights.
DynMapTree< Node *, Distance_Type > compute_nodes_weights()
Returns a mapping with the shortest distances to each node obtained after executing the Bellman-Ford ...
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Generic key-value map implemented on top of a binary search tree.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Data & find(const Key &key)
Find the value associated with key.
Johnson's algorithm for all-pairs shortest paths.
Definition Johnson.H:216
static Weight reweight(const Distance_Type &w, const Distance_Type &hu, const Distance_Type &hv)
Definition Johnson.H:387
std::vector< Weight > reach
Definition Johnson.H:306
std::vector< size_t > via
Definition Johnson.H:308
Path< GT > find_path(Node *src, Node *tgt)
Find the shortest path from source to target.
Definition Johnson.H:913
Johnson(const Johnson &)=delete
Johnson is not copyable: a copy would point to the nodes of the copy of the graph that this one keeps...
std::vector< Wide > wide_weight
Definition Johnson.H:322
static constexpr bool Integer
Definition Johnson.H:225
Johnson(Johnson &&)=default
Move constructor: the tree that is kept moves too.
void paint_wide(size_t s)
Definition Johnson.H:618
Distance_Type distance_to(size_t s, size_t t) const
Definition Johnson.H:493
void paint_from(size_t s)
Definition Johnson.H:622
std::vector< Node * > nodes
The node of each number.
Definition Johnson.H:267
size_t number_of(Node *p) const
Definition Johnson.H:377
GT & get_reweighted_graph() noexcept
Get access to the internal reweighted graph.
Definition Johnson.H:1017
static Distance_Type wide_unweighted(const Wide &d_prime, const Wide &hs, const Wide &ht)
Definition Johnson.H:480
void spread_too_far()
Definition Johnson.H:519
static constexpr Distance_Type unreachable() noexcept
Definition Johnson.H:446
bool is_initialized() const noexcept
Check if the algorithm has been initialized.
Definition Johnson.H:867
std::vector< size_t > out_first
Definition Johnson.H:275
DynMapTree< std::pair< Node *, Node * >, Distance_Type > compute_all_pairs_distances()
Compute the shortest distance for all pairs.
Definition Johnson.H:958
std::vector< std::pair< Wide, size_t > > wide_heap
Definition Johnson.H:324
std::vector< std::pair< Weight, size_t > > heap
Definition Johnson.H:314
auto & reach_of() noexcept
Definition Johnson.H:338
std::vector< Weight > out_weight
Definition Johnson.H:277
static bool add(const Weight &a, const Weight &b, Weight &sum)
Definition Johnson.H:398
void wide_potentials(const std::vector< Shown_Arc > &shown)
Definition Johnson.H:785
Distance_Type get_potential(Node *node) const
Get the node potential (h value) for a node.
Definition Johnson.H:992
static void write_info(Arc *copy, const Wide &w)
Definition Johnson.H:433
void wide_arcs(const std::vector< Shown_Arc > &shown)
Definition Johnson.H:809
GT reweighted
Copy of the graph.
Definition Johnson.H:265
std::vector< unsigned char > state
Definition Johnson.H:305
std::vector< Wide > wide_reach
Definition Johnson.H:323
static bool add(const Wide &a, const Wide &b, Wide &sum)
Definition Johnson.H:409
typename std::conditional_t< Integer, std::make_unsigned< std::remove_cv_t< Distance_Type > >, std::type_identity< Distance_Type > >::type Weight
Definition Johnson.H:234
const GT * orig_graph
Definition Johnson.H:264
void paint(size_t s)
Definition Johnson.H:549
static constexpr size_t None
Definition Johnson.H:244
typename GT::Arc Arc
Definition Johnson.H:219
Johnson(const GT &g, Distance d=Distance(), SA __sa=SA())
Construct a Johnson's all-pairs shortest paths executor.
Definition Johnson.H:659
Distance_Type distance_apart(size_t s, size_t t) const
Definition Johnson.H:506
auto & weights_of() noexcept
Definition Johnson.H:329
static Distance_Type unweighted(const Weight &d_prime, const Distance_Type &hs, const Distance_Type &ht)
Definition Johnson.H:459
std::vector< size_t > parent
Definition Johnson.H:307
typename Distance::Distance_Type Distance_Type
Definition Johnson.H:220
std::vector< Arc * > out_arc
Definition Johnson.H:278
Johnson()=default
Default constructor (uninitialized state)
typename GT::Node Node
Definition Johnson.H:218
std::vector< Node * > copies
Its copy in the reweighted graph.
Definition Johnson.H:268
struct Aleph::Johnson::Kept_Source kept
DynMapTree< Node *, size_t > number
Of each node of the graph, from 0.
Definition Johnson.H:266
auto & heap_of() noexcept
Definition Johnson.H:347
Node * get_copy_node(Node *orig) const
Get the copy of a node in the reweighted graph.
Definition Johnson.H:1032
Distance_Type get_distance(Node *src, Node *tgt)
Get the shortest distance from source to target.
Definition Johnson.H:885
const GT & get_reweighted_graph() const noexcept
Get const access to the internal reweighted graph.
Definition Johnson.H:1024
Johnson & operator=(const Johnson &)=delete
Johnson is not copyable: a copy would point to the nodes of the copy of the graph that this one keeps...
void narrow_potentials(Potential_Graph &pg, const std::vector< typename Potential_Graph::Node * > &pnodes)
Definition Johnson.H:770
static constexpr bool Signed_Integer
Definition Johnson.H:239
static void write_info(Arc *copy, const Weight &w)
Definition Johnson.H:417
std::vector< size_t > out_target
Definition Johnson.H:276
std::vector< Distance_Type > h
Its potential, from Bellman-Ford.
Definition Johnson.H:269
std::vector< Wide > wide_h
Definition Johnson.H:321
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Path on a graph.
Definition tpl_graph.H:3832
void init(Node *start_node)
Set the first node of a path.
Definition tpl_graph.H:3947
void append(Arc *arc)
Append an arc to the path.
Definition tpl_graph.H:4052
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
size_t resize(size_t new_size)
Resizes the hash table to a new capacity.
Definition hashDry.H:888
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Main namespace for Aleph-w library functions.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Kept_Source(Kept_Source &&other) noexcept
Definition Johnson.H:363
Kept_Source & operator=(Kept_Source &&other) noexcept
Definition Johnson.H:369
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Represents a missing value.
An integer of 128 bits, in two words of 64.
Definition Johnson.H:108
friend constexpr Wide operator-(const Wide &a, const Wide &b) noexcept
a - b, modulo 2^128
Definition Johnson.H:131
static constexpr Wide of(const T x) noexcept
The integer x, in two's complement.
Definition Johnson.H:114
friend constexpr Wide operator+(const Wide &a, const Wide &b) noexcept
a + b, modulo 2^128
Definition Johnson.H:124
std::uint64_t hi
The high word.
Definition Johnson.H:109
friend constexpr bool operator<(const Wide &a, const Wide &b) noexcept
Whether a < b, as unsigned integers.
Definition Johnson.H:141
friend constexpr bool operator==(const Wide &a, const Wide &b) noexcept=default
Whether a and b are the same integer.
std::uint64_t lo
The low word.
Definition Johnson.H:110
static constexpr bool signed_less(const Wide &a, const Wide &b) noexcept
Whether a < b, as integers in two's complement.
Definition Johnson.H:147
Distance accessor.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Alias for htlist.H (DynList implementation).
Dynamic key-value map based on balanced binary search trees.
Generic graph and digraph implementations.