-
Notifications
You must be signed in to change notification settings - Fork 1
/
dijkstra.linq
1458 lines (1138 loc) · 45.5 KB
/
dijkstra.linq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<Query Kind="Program">
<Namespace>LINQPad.Controls</Namespace>
<Namespace>System.ComponentModel</Namespace>
</Query>
// Copyright (C) 2020, 2021 Eliah Kagan <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#load "./helpers.linq"
#load "./generator.linq"
#nullable enable
/// <summary>Configuration options not exposed by the controller.</summary>
internal static class Options {
internal static bool DisableInputWhileProcessing => true;
internal static bool OfferWrongQueue => false;
internal static bool DebugFibonacciHeap => false;
}
/// <summary>LINQ-style extension methods.</summary>
internal static class EnumerableExtensions {
internal static TSource
MinBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
=> source.MinBy(keySelector, Comparer<TKey>.Default);
internal static TSource
MinBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey> comparer)
{
using var en = source.GetEnumerator();
if (!en.MoveNext())
throw new InvalidOperationException("Source contains no elements");
var min = en.Current;
var minKey = keySelector(min);
while (en.MoveNext()) {
var curKey = keySelector(en.Current);
if (comparer.Compare(curKey, minKey) < 0) {
min = en.Current;
minKey = curKey;
}
}
return min;
}
}
/// <summary>
/// String parsing methods used in multiple (conceptually unrealted) places.
/// </summary>
internal static class StringExtensions {
internal static string Before(this string text, char delimiter)
{
var end = text.IndexOf(delimiter);
return end == -1 ? text : text[0..end];
}
}
/// <summary>
/// Supplies a custom informal name for a data structure.
/// <see cref="TypeExtensions.GetInformalName(System.Type)"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,
Inherited = false, AllowMultiple = false)]
internal sealed class InformalNameAttribute : Attribute {
internal InformalNameAttribute(string informalName)
=> InformalName = informalName;
internal string InformalName { get; }
}
/// <summary>Convenience functionality for using reflection.</summary>
internal static class TypeExtensions {
internal static string GetInformalName(this Type type)
{
var attrs = type.GetCustomAttributes(typeof(InformalNameAttribute),
inherit: false);
if (attrs.Length != 0)
return ((InformalNameAttribute)attrs[0]).InformalName;
return string.Join(" ", GetLowerCamelWords(type.Name.Before('`')));
}
internal static Func<T> CreateSupplier<T>(this Type type) where T : notnull
=> () => type.CreateAsNonnull<T>();
private static IEnumerable<string> GetLowerCamelWords(string name)
=> camelParser.Matches(name).Select(match => match.Value.ToLower());
private static T CreateAsNonnull<T>(this Type type) where T : notnull
{
var instance = Activator.CreateInstance(type, nonPublic: true);
if (instance == null) {
throw new NotSupportedException(
"Bug: non-nullable type instantiated null");
}
return (T)instance;
}
private static readonly Regex camelParser =
new Regex(@"(?:^.|\p{Lu})\P{Lu}*");
}
/// <summary>
/// Priority queue operations for Prim's and Dijkstra's algorithms.
/// </summary>
internal interface IPriorityQueue<TKey, TValue> {
/// <summary>The number of mappings stored in the heap.</summary>
int Count { get; }
/// <summary>
/// Maps <c>key</c> to <c>value</c> if it is not already present with
/// a smaller value.
/// </summary>
/// <returns>
/// <c>true</c> iff a mapping was inserted or modified (decreased).
/// </returns>
bool InsertOrDecrease(TKey key, TValue value);
/// <summary>Extracts a mapping of minimal value.</summary>
/// <returns>The extracted mapping.</returns>
KeyValuePair<TKey, TValue> ExtractMin();
}
/// <summary>
/// A naive priority queue for Prim's and Dijkstra's algorithms.
/// </summary>
/// <remarks>O(1) insert/decrease. O(n) extract-min.</remarks>
internal sealed class UnsortedPriorityQueue<TKey, TValue>
: IPriorityQueue<TKey, TValue> where TKey : notnull {
internal UnsortedPriorityQueue() : this(Comparer<TValue>.Default) { }
internal UnsortedPriorityQueue(IComparer<TValue> comparer)
=> _comparer = comparer;
public int Count => _entries.Count;
public bool InsertOrDecrease(TKey key, TValue value)
{
if (_entries.TryGetValue(key, out var oldValue)
&& _comparer.Compare(oldValue, value) <= 0)
return false;
_entries[key] = value;
return true;
}
public KeyValuePair<TKey, TValue> ExtractMin()
{
var entry = _entries.MinBy(entry => entry.Value, _comparer);
_entries.Remove(entry);
return entry;
}
private readonly IComparer<TValue> _comparer;
private readonly IDictionary<TKey, TValue> _entries =
new Dictionary<TKey, TValue>();
}
/// <summary>
/// A priority queue for Prim's and Dijkstra's algorithms, based on a
/// self-balancing binary search tree.
/// </summary>
/// <remarks>
/// O(log n) insert/decrease. O(log n) extract-min.
/// <para>
/// Prefer <see cref="BinaryHeap"/> to this. They have the same asymptotic
/// runtimes, but this is likely to be slower by a constant factor.
/// </para>
/// <para>
/// This uses <see cref="System.Collections.Generic.SortedSet"/>, which is
/// implemented as a red-black tree.
/// </para>
/// </remarks>
[InformalName("red-black tree")]
internal sealed class SortedSetPriorityQueue<TKey, TValue>
: IPriorityQueue<TKey, TValue> where TKey : notnull {
// TODO: Reimplement this to use a tree multiset (instead of a tree set, as
// it does now) to lift the strange reliance on TKey being totally ordered.
// .NET doesn't ship one, but one could be pulled in as a nuget dependency,
// implemented as a general-purpose sorted multiset elsewhere in this
// program, or (this might be best) implemented in a special-purpose way in
// this class, so _tree hands out node references for _map to map keys to.
internal SortedSetPriorityQueue() : this(Comparer<TValue>.Default) { }
internal SortedSetPriorityQueue(IComparer<TValue> comparer)
{
_valueComparer = comparer;
_tree = new SortedSet<KeyValuePair<TKey, TValue>>(
GetEntryComparer(comparer));
}
public int Count => _tree.Count;
public bool InsertOrDecrease(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var oldValue)) {
if (_valueComparer.Compare(oldValue, value) <= 0) return false;
_tree.Remove(KeyValuePair.Create(key, oldValue));
}
_map[key] = value;
_tree.Add(KeyValuePair.Create(key, value));
return true;
}
public KeyValuePair<TKey, TValue> ExtractMin()
{
if (Count == 0)
throw new InvalidOperationException("Nothing to extract");
var min = _tree.Min;
_tree.Remove(min);
_map.Remove(min.Key);
return min;
}
private static IComparer<KeyValuePair<TKey, TValue>>
GetEntryComparer(IComparer<TValue> valueComparer)
=> Comparer<KeyValuePair<TKey, TValue>>.Create((lhs, rhs) => {
var byValue = valueComparer.Compare(lhs.Value, rhs.Value);
if (byValue != 0) return byValue;
return Comparer<TKey>.Default.Compare(lhs.Key, rhs.Key);
});
private readonly IComparer<TValue> _valueComparer;
private readonly SortedSet<KeyValuePair<TKey, TValue>> _tree;
private readonly IDictionary<TKey, TValue> _map =
new Dictionary<TKey, TValue>();
}
/// <summary>
/// A binary minheap providing priority queue operations for Prim's and
/// Dijkstra's algorithms. Sometimes called a "heap + map" data structure.
/// </summary>
/// <remarks>O(log n) insert/decrease. O(log n) extract-min.</remarks>
internal sealed class BinaryHeap<TKey, TValue> : IPriorityQueue<TKey, TValue>
where TKey : notnull {
internal BinaryHeap() : this(Comparer<TValue>.Default) { }
internal BinaryHeap(IComparer<TValue> comparer) => _comparer = comparer;
public int Count => _heap.Count;
public bool InsertOrDecrease(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var index)) {
// Stop if the stored value is no greater than the given value.
if (OrderOK(_heap[index].Value, value)) return false;
_heap[index] = KeyValuePair.Create(key, value);
} else {
index = Count;
_heap.Add(KeyValuePair.Create(key, value));
}
SiftUp(index);
return true;
}
public KeyValuePair<TKey, TValue> ExtractMin()
{
if (Count == 0)
throw new InvalidOperationException("Nothing to extract");
var entry = _heap[0];
var last = Count - 1;
if (last == 0) {
_heap.Clear();
_map.Clear();
} else {
_map.Remove(entry.Key);
_heap[0] = _heap[last];
_heap.RemoveAt(last);
SiftDown(0);
}
return entry;
}
private const int None = -1;
private void SiftUp(int child)
{
var entry = _heap[child];
while (child != 0) {
var parent = (child - 1) / 2;
if (OrderOK(_heap[parent].Value, entry.Value)) break;
Set(child, _heap[parent]);
child = parent;
}
Set(child, entry);
}
private void SiftDown(int parent)
{
var entry = _heap[parent];
for (; ; ) {
var child = PickChild(parent);
if (child == None || OrderOK(entry.Value, _heap[child].Value))
break;
Set(parent, _heap[child]);
parent = child;
}
Set(parent, entry);
}
private int PickChild(int parent)
{
var left = parent * 2 + 1;
if (left >= Count) return None;
var right = left + 1;
return right == Count || OrderOK(_heap[left].Value, _heap[right].Value)
? left
: right;
}
private bool OrderOK(TValue parentValue, TValue childValue)
=> _comparer.Compare(parentValue, childValue) <= 0;
private void Set(int index, KeyValuePair<TKey, TValue> entry)
{
_heap[index] = entry;
_map[entry.Key] = index;
}
private readonly IComparer<TValue> _comparer;
private readonly IList<KeyValuePair<TKey, TValue>> _heap =
new List<KeyValuePair<TKey, TValue>>();
private readonly IDictionary<TKey, int> _map = new Dictionary<TKey, int>();
}
/// <summary>
/// A Fibonacci minheap providing priority queue operations for Prim's and
/// Dijkstra's algorithms.
/// </summary>
/// <remarks>O(1) insert/decrease. O(log n) extract-min. (Amortized.)</remarks>
[InformalName("Fibonacci heap")] // Otherwise it would not show up capitalized.
internal sealed class FibonacciHeap<TKey, TValue>
: IPriorityQueue<TKey, TValue> where TKey : notnull {
internal FibonacciHeap() : this(Comparer<TValue>.Default) { }
internal FibonacciHeap(IComparer<TValue> comparer)
=> _comparer = comparer;
public int Count => _map.Count;
public bool InsertOrDecrease(TKey key, TValue value)
{
if (!_map.TryGetValue(key, out var node)) {
Insert(key, value);
} else if (_comparer.Compare(value, node.Value) < 0) {
node.Value = value;
Decrease(node);
} else {
return false;
}
return true;
}
public KeyValuePair<TKey, TValue> ExtractMin()
{
if (Count == 0)
throw new InvalidOperationException("Nothing to extract");
var node = ExtractMinNode();
_map.Remove(node.Key);
if (Options.DebugFibonacciHeap) this.Dump(noTotals: true);
return KeyValuePair.Create(node.Key, node.Value);
}
private sealed class Node {
internal Node(TKey key, TValue value)
=> (Key, Value, Prev, Next) = (key, value, this, this);
internal TKey Key { get; }
internal TValue Value { get; set; }
internal Node? Parent { get; set; } = null;
internal Node Prev { get; set; }
internal Node Next { get; set; }
internal Node? Child { get; set; } = null;
internal int Degree { get; set; } = 0;
internal bool Mark { get; set; } = false;
private object ToDump() => new {
Key,
Value,
Degree,
Mark,
Children = NodesInChain(Child)
};
}
/// <summary>Yields this node (if any) and its siblings, lazily.</summary>
/// <remarks>
/// Call <c>ToList</c> if adding or removing nodes during iteration.
/// </remarks>
private static IEnumerable<Node> NodesInChain(Node? node)
{
if (node == null) yield break;
yield return node;
for (var sibling = node.Next; sibling != node; sibling = sibling.Next)
yield return sibling;
}
private static readonly double GoldenRatio = (1.0 + Math.Sqrt(5.0)) / 2.0;
/// <summary>The maximum degree is no more than this.</summary>
private int DegreeCeiling => (int)Math.Log(a: Count, newBase: GoldenRatio);
private void Insert(TKey key, TValue value)
{
var node = new Node(key, value);
InsertNode(node);
_map.Add(key, node);
}
private void InsertNode(Node node)
{
Debug.Assert((_min == null) == (Count == 0));
Debug.Assert(node.Next == node && node.Parent == null);
if (_min == null) {
_min = node;
} else {
node.Prev = _min;
node.Next = _min.Next;
node.Prev.Next = node.Next.Prev = node;
if (_comparer.Compare(node.Value, _min.Value) < 0) _min = node;
}
}
private Node ExtractMinNode()
{
// TODO: Factor some parts out into helper methods.
Debug.Assert(_min != null);
var parent = _min;
if (parent.Child != null) {
var child = parent.Child;
// Tell the children their root is about to go away.
do { // for each child
child.Parent = null;
child = child.Next;
} while (child != parent.Child);
// Splice the children up into the root chain.
child.Prev.Next = parent.Next;
parent.Next.Prev = child.Prev;
child.Prev = parent;
parent.Next = child;
}
if (parent == parent.Next) {
// There are no other roots, so just make the forest empty.
_min = null;
} else {
// Remove the minimum node.
_min = parent.Prev.Next = parent.Next;
parent.Next.Prev = parent.Prev;
parent.Prev = parent.Next = parent; // to avoid confusion
Consolidate();
}
return parent;
}
private void Consolidate()
{
var roots_by_degree = new Node?[DegreeCeiling + 1];
// Link trees together so no two roots have the same degree.
foreach (var root in NodesInChain(_min).ToList()) {
var parent = root;
var degree = parent.Degree;
for (; ; ) {
var child = roots_by_degree[degree];
if (child == null) break;
if (_comparer.Compare(child.Value, parent.Value) < 0)
(parent, child) = (child, parent);
Link(parent, child);
roots_by_degree[degree++] = null;
}
roots_by_degree[degree] = parent;
}
// Reattach the linked list of roots, at the minimum node.
_min = roots_by_degree
.OfType<Node>() // skip nulls
.MinBy(node => node.Value, _comparer);
}
private void Link(Node parent, Node child)
{
Debug.Assert(parent.Parent == null && child.Parent == null);
child.Prev.Next = child.Next;
child.Next.Prev = child.Prev;
child.Parent = parent;
child.Mark = false;
if (parent.Child == null) {
parent.Child = child.Prev = child.Next = child;
} else {
child.Prev = parent.Child;
child.Next = parent.Child.Next;
child.Prev.Next = child.Next.Prev = child;
}
++parent.Degree;
}
private void Decrease(Node child)
{
if (child.Parent != null) {
var parent = child.Parent; // Remember it for CascadingCut.
if (_comparer.Compare(child.Value, parent.Value) < 0) {
Cut(child);
CascadingCut(parent);
}
}
Debug.Assert(_min != null);
if (_comparer.Compare(child.Value, _min.Value) < 0) _min = child;
}
private void Cut(Node child)
{
Debug.Assert(child.Parent != null);
Debug.Assert(_min != null);
if (child == child.Next) {
Debug.Assert(child.Parent.Child == child);
child.Parent.Child = null;
} else {
if (child.Parent.Child == child) child.Parent.Child = child.Next;
child.Prev.Next = child.Next;
child.Next.Prev = child.Prev;
}
--child.Parent.Degree;
child.Parent = null;
child.Mark = false;
child.Prev = _min;
child.Next = _min.Next;
child.Prev.Next = child.Next.Prev = child;
}
private void CascadingCut(Node node)
{
// TODO: Maybe implement this iteratively.
if (node.Parent == null) return;
if (node.Mark) {
var parent = node.Parent; // Remember it for the recursive call.
Cut(node);
CascadingCut(parent);
} else {
node.Mark = true;
}
}
private object ToDump() => new { Count, Roots = NodesInChain(_min) };
private Node? _min = null;
private readonly IDictionary<TKey, Node> _map =
new Dictionary<TKey, Node>();
private readonly IComparer<TValue> _comparer;
}
/// </summary>
/// A fake priority queue that swallows all input, for testing.
/// </summary>
[InformalName("wrongqueue is wrooooooong")]
internal sealed class WrongQueue<TKey, TValue> : IPriorityQueue<TKey, TValue> {
public int Count => 0;
public bool InsertOrDecrease(TKey key, TValue value) => false;
public KeyValuePair<TKey, TValue> ExtractMin()
=> throw new InvalidOperationException(
$"Can't extract from {nameof(WrongQueue<TKey, TValue>)},"
+ " which only pretends to take input");
}
/// <summary>
/// Encapsulates a method that provides a priority queue suitable for
/// and Prim's and Dijkstra's algorithm on a graph with integer weights.
/// </summary>
/// <remarks>
/// See <see cref="IPriorityQueue"/> and <see cref="Graph"/>.
/// </remarks>
internal delegate IPriorityQueue<int, long> PQSupplier();
/// <summary>Convenience functions for marked edges.</summary>
internal static class MarkedEdge {
internal static MarkedEdge<T> Create<T>(Edge edge, T mark)
=> new MarkedEdge<T>(edge, mark);
}
/// <summary>A marked edge in a weighted directed graph.</summary>
internal readonly struct MarkedEdge<T> {
internal MarkedEdge(Edge edge, T mark)
=> (_edge, Mark) = (edge, mark);
internal int Src => _edge.Src;
internal int Dest => _edge.Dest;
internal int Weight => _edge.Weight;
internal T Mark { get; }
private object ToDump() => new { Src, Dest, Weight, Mark };
private readonly Edge _edge;
}
/// <summary>
/// A weighted directed graph represented as an adjacency list.
/// </summary>
internal sealed class Graph {
internal Graph(int order)
{
if (order < 0) {
throw new ArgumentOutOfRangeException(
paramName: nameof(order),
message: "Can't have negatively many vertices");
}
_adj = new List<IList<(int dest, int weight)>>(capacity: order);
for (var vertex = 0; vertex != order; ++vertex)
_adj.Add(new List<(int, int)>());
}
internal int Order => _adj.Count;
internal void Add(int src, int dest, int weight)
{
CheckVertex(nameof(src), src);
CheckVertex(nameof(dest), dest);
if (weight < 0) {
throw new ArgumentException(
paramName: nameof(weight),
message: "Negative weights are not supported");
}
_adj[src].Add((dest, weight));
}
internal ParentsTree ComputeShortestPaths(int start, PQSupplier pqSupplier)
{
CheckVertex(nameof(start), start);
var parents = new int?[Order];
var done = new BitArray(Order);
var heap = pqSupplier();
for (heap.InsertOrDecrease(start, 0L); heap.Count != 0; ) {
var (src, cost) = heap.ExtractMin();
done[src] = true;
foreach (var (dest, weight) in _adj[src]) {
if (!done[dest] && heap.InsertOrDecrease(dest, cost + weight))
parents[dest] = src;
}
}
return new ParentsTree(this, parents);
}
internal IEnumerable<Edge> Edges
{
get {
foreach (var src in Enumerable.Range(0, Order)) {
foreach (var (dest, weight) in _adj[src])
yield return new Edge(src, dest, weight);
}
}
}
internal EdgeSelection
SelectEdges(Func<(int src, int dest), bool> predicate)
{
var parallels = GroupParallelEdges();
IEnumerable<MarkedEdge<bool>> Emit()
{
foreach (var (endpoints, group) in parallels) {
if (predicate(endpoints)) {
var indices = Enumerable.Range(0, group.Count);
var bestIndex = indices.MinBy(i => group[i].Weight);
foreach (var index in indices) {
yield return MarkedEdge.Create(group[index],
index == bestIndex);
}
} else {
foreach (var edge in group)
yield return MarkedEdge.Create(edge, false);
}
}
}
return new EdgeSelection(Order, Emit());
}
private IReadOnlyDictionary<(int src, int dest), IReadOnlyList<Edge>>
GroupParallelEdges()
{
var parallels = new Dictionary<(int src, int dest),
IReadOnlyList<Edge>>();
foreach (var group in Edges.GroupBy(edge => (edge.Src, edge.Dest)))
parallels.Add(group.Key, group.ToList());
return parallels;
}
private void CheckVertex(string paramName, int vertex)
{
if (!(0 <= vertex && vertex < Order)) {
throw new ArgumentOutOfRangeException(
paramName: paramName,
message: $"Vertex {vertex} out of range");
}
}
private readonly IList<IList<(int dest, int weight)>> _adj;
}
/// <summary>A tree in a graph, represented as a parents list.</summary>
internal sealed class ParentsTree : IEquatable<ParentsTree>,
IReadOnlyList<int?> {
/// <summary>Constructs a parents tree.</summary>
/// <remarks>Does not range-check or cycle-check the parents.</remarks>
internal ParentsTree(Graph graph, IReadOnlyList<int?> parents)
=> (Supergraph, _parents) = (graph, parents);
internal Graph Supergraph { get; }
internal int Order => _parents.Count;
public bool Equals(ParentsTree? other)
=> other != null
&& Supergraph == other.Supergraph
&& _parents.SequenceEqual(other._parents);
public override bool Equals(object? other)
=> Equals(other as ParentsTree);
public override int GetHashCode()
{
const int seed = 17;
const int multiplier = 8191;
var code = seed;
unchecked {
code = code * multiplier + Supergraph.GetHashCode();
foreach (var parent in _parents)
code = code * multiplier + parent.GetHashCode();
}
return code;
}
public int? this[int child] => _parents[child];
int IReadOnlyCollection<int?>.Count => Order;
public IEnumerator<int?> GetEnumerator() => _parents.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
internal EdgeSelection ToEdgeSelection()
=> Supergraph.SelectEdges(edge => _parents[edge.dest] == edge.src);
private object ToDump()
=> _parents.Select((Parent, Child) => new { Child, Parent });
private readonly IReadOnlyList<int?> _parents;
}
/// <summary>An immutable list of edges with boolean markings.</summary>
internal sealed class EdgeSelection : IReadOnlyList<MarkedEdge<bool>> {
internal EdgeSelection(int order, IEnumerable<MarkedEdge<bool>> edges)
=> (Order, _edges) = (order, edges.ToList());
public MarkedEdge<bool> this[int index] => _edges[index];
public int Count => _edges.Count;
public IEnumerator<MarkedEdge<bool>> GetEnumerator()
=> _edges.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
internal int Order { get; }
internal DotCode ToDotCode(string description)
{
const int indent = 4;
var margin = new string(' ', indent);
var builder = new StringBuilder();
builder.AppendLine($"digraph \"{description}\" {{");
// Emit the vertices in ascending order, to be drawn as circles.
foreach (var vertex in Enumerable.Range(0, Order))
builder.AppendLine($"{margin}{vertex} [shape=\"circle\"]");
builder.AppendLine();
// Emit the edges in the order given, colorized according to selection.
foreach (var edge in _edges) {
var endpoints = $"{edge.Src} -> {edge.Dest}";
var color = $"color=\"{(edge.Mark ? "red" : "gray")}\"";
var label = $"label=\"{edge.Weight}\"";
builder.AppendLine($"{margin}{endpoints} [{color} {label}]");
}
builder.AppendLine("}");
return new DotCode(builder.ToString());
}
private readonly IReadOnlyList<MarkedEdge<bool>> _edges;
}
/// <summary>DOT code for input to GraphViz.</summary>
/// <remarks>
/// Currently this just represents DOT as raw text (not an AST or anything).
/// </remarks>
internal sealed class DotCode {
internal DotCode(string code) => Code = code;
internal string Code { get; }
/// <summary>Runs <c>dot</c> to create a temporary SVG file.</summary>
internal object ToSvg()
{
static void Carp(Exception e, string suggestion)
{
var message =
"Can't convert DOT to SVG with the \"dot\" command."
+ suggestion;
if (Thread.CurrentThread.IsThreadPoolThread)
e.Dump(message);
else
"(See dumped exception below.)".Dump(message);
}
try {
return DoToSvg();
} catch (Win32Exception e) {
Carp(e, " Is GraphViz installed?");
throw;
} catch (FileNotFoundException e) {
Carp(e, Environment.NewLine + Environment.NewLine
+ "Do you need to run \"dot -c\"?"
+ " (This is only a guess.)");
throw;
}
}
private object DoToSvg()
{
var dir = Path.GetTempPath();
var guid = Guid.NewGuid();
var dotPath = Path.Combine(dir, $"{guid}.dot");
var svgPath = Path.Combine(dir, $"{guid}.svg");
using (var writer = File.CreateText(dotPath))
writer.Write(Code);
var proc = new Process();
proc.StartInfo.ArgumentList.Add("-Tsvg");
proc.StartInfo.ArgumentList.Add("-o");
proc.StartInfo.ArgumentList.Add(svgPath);
proc.StartInfo.ArgumentList.Add(dotPath);
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "dot";
proc.StartInfo.RedirectStandardInput = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
// FIXME: Read standard error?
proc.WaitForExit();
// FIXME: Look at exit code?
// TODO: Offer to run "dot -c" for the user, if dot fails and reports:
// Format: "svg" not recognized. Use one of:
// (When this problem happens, usually that is the full message.)
return Util.RawHtml(File.ReadAllText(svgPath));
}
private object ToDump() => new TextArea(Code, columns: 40);
}
/// <summary>UI to accept a graph description and trigger a run.</summary>
internal sealed class Controller {
internal sealed class Builder {
internal Builder Order(int order)
=> SetField(nameof(order), ref _order, order);
internal Builder Edge(int src, int dest, int weight)
{
_edges.Add(new Edge(src, dest, weight));
return this;
}
internal Builder Source(int source)
=> SetField(nameof(source), ref _source, source);
internal Builder PQ(Type type, bool selected = true)
{
_priorityQueues.Add(new PriorityQueueItem(type, selected));
return this;
}
internal Controller Build()
=> new Controller(initialOrder: GetField("order", _order),
initialEdges: BuildEdgesText(),
initialSource: GetField("source", _source),
priorityQueues: _priorityQueues);
private Builder SetField(string name, ref int? field, int value)
{
if (field != null) {
throw new ArgumentException(
paramName: name,
message: "property already set");
}
field = value;
return this;
}