This documentation is automatically generated by online-judge-tools/verification-helper

:heavy_check_mark: src/graph/dijkstra.cr

Depends on

Verified with

Code

require "../datastructure/binary_heap"
require "../graph"

module Graph(Edge, Edge2)
  # Returns the array of distance of each node from *start* or `nil`.
  def dijkstra(start : Int)
    raise ArgumentError.new unless 0 <= start < size
    que = BinaryHeap({Int32, typeof(first.cost)}).new { |(v1, d1), (v2, d2)| d1 <=> d2 }
    que << {start, typeof(first.cost).zero}
    dist = Array(typeof(first.cost)?).new(size, nil)
    dist[start] = typeof(first.cost).zero

    until que.empty?
      v, d = que.pop
      next if dist[v].try { |dist_v| dist_v < d }
      current_dist = dist[v].not_nil!
      graph[v].each do |edge|
        next_dist = current_dist + edge.cost
        if dist[edge.to].nil? || dist[edge.to].not_nil! > next_dist
          dist[edge.to] = next_dist
          que << {edge.to, next_dist}
        end
      end
    end
    dist
  end

  # Returns the array of distance of each node from *start*.
  def dijkstra!(start : Int)
    dijkstra(start).map(&.not_nil!)
  end

  # Returns the distance of *start* to *goal* or `nil`.
  def dijkstra(start : Int, goal : Int)
    raise ArgumentError.new unless 0 <= start < size && 0 <= goal < size
    que = BinaryHeap({Int32, typeof(first.cost)}).new { |(v1, d1), (v2, d2)| d1 <=> d2 }
    que << {start, typeof(first.cost).zero}
    dist = Array(typeof(first.cost)?).new(size, nil)
    dist[start] = typeof(first.cost).zero

    until que.empty?
      v, d = que.pop
      return d if v == goal
      next if dist[v].try { |dist_v| dist_v < d }
      current_dist = dist[v].not_nil!
      graph[v].each do |edge|
        next_dist = current_dist + edge.cost
        if dist[edge.to].nil? || dist[edge.to].not_nil! > next_dist
          dist[edge.to] = next_dist
          que << {edge.to, next_dist}
        end
      end
    end
  end

  # Returns the distance of *start* to *goal*.
  def dijkstra!(start : Int, goal : Int)
    dijkstra(start, goal).not_nil!
  end

  def dijkstra_with_prev(start : Int)
    raise ArgumentError.new unless 0 <= start < size
    que = BinaryHeap({Int32, typeof(first.cost)}).new { |(v1, d1), (v2, d2)| d1 <=> d2 }
    que << {start, typeof(first.cost).zero}
    dist = Array(typeof(first.cost)?).new(size, nil)
    dist[start] = typeof(first.cost).zero
    prev = Array(Int32?).new(size, nil)

    until que.empty?
      v, d = que.pop
      next if dist[v].try { |dist_v| dist_v < d }
      current_dist = dist[v].not_nil!
      graph[v].each do |edge|
        next_dist = current_dist + edge.cost
        if dist[edge.to].nil? || dist[edge.to].not_nil! > next_dist
          dist[edge.to] = next_dist
          prev[edge.to] = v
          que << {edge.to, next_dist}
        end
      end
    end
    {dist, prev}
  end

  def dijkstra_with_path(start : Int, goal : Int)
    dist, prev = dijkstra_with_prev(start)
    if d = dist[goal]
      {d, Graph.restore_path(prev, goal)}
    end
  end

  def self.restore_path(prev : Array(Int32?), v : Int) : Array(Int32)
    v = v.to_i
    path = [v]
    while v = prev[v]
      path << v
    end
    path.reverse
  end
end
# require "../datastructure/binary_heap"
class BinaryHeap(T)
  # Creates a new empty heap.
  def initialize
    @heap = Array(T).new
    @compare_proc = nil
  end

  # Creates a new empty heap backed by a buffer that is initially *initial_capacity* big (default: `0`).
  #
  # ```
  # a = BinaryHeap.new(3)
  # a << 3 << 1 << 2
  # a.pop # => 1
  # a.pop # => 2
  # a.pop # => 3
  # ```
  def initialize(initial_capacity : Int = 0)
    @heap = Array(T).new(initial_capacity)
    @compare_proc = nil
  end

  # Creates a new heap from the elements in *enumerable*.
  #
  # ```
  # a = BinaryHeap.new [3, 1, 2]
  # a.pop # => 1
  # a.pop # => 2
  # a.pop # => 3
  # ```
  def initialize(enumerable : Enumerable(T))
    initialize
    enumerable.each { |x| add(x) }
  end

  # Creates a new empty heap with the custom comperator.
  #
  # The block must implement a comparison between two elements *a* and *b*, where `a < b` returns `-1`,
  # `a == b` returns `0`, and `a > b` returns `1`. The comparison operator `#<=>` can be used for this.
  #
  # ```
  # a = BinaryHeap.new [3, 1, 2]
  # a.pop # => 1
  # b = BinaryHeap.new [3, 1, 2] { |a, b| b <=> a }
  # b.pop # => 3
  # ```
  def initialize(initial_capacity : Int = 0, &block : T, T -> Int32?)
    @heap = Array(T).new(initial_capacity)
    @compare_proc = block
  end

  # :ditto:
  def initialize(enumerable : Enumerable(T), &block : T, T -> Int32?)
    initialize &block
    enumerable.each { |x| add(x) }
  end

  include Enumerable(T)
  include Iterable(T)

  def_clone

  # Returns true if both heap have the same elements.
  def ==(other : BinaryHeap(T)) : Bool
    return false if size != other.size
    @heap.sort == other.@heap.sort
  end

  # Returns the number of elements in the heap.
  def size : Int32
    @heap.size
  end

  # Returns `true` if `self` is empty, `false` otherwise.
  def empty? : Bool
    @heap.empty?
  end

  # Removes all elements from the heap and returns `self`.
  def clear : self
    @heap.clear
    self
  end

  # Returns the lowest value in the `self`.
  # If the `self` is empty, calls the block and returns its value.
  def top(&block)
    @heap.first { yield }
  end

  # Returns the lowest value in the `self`.
  # If the `self` is empty, returns `nil`.
  def top? : T?
    top { nil }
  end

  # Returns the lowest value in the `self`.
  # If the `self` is empty, raises `IndexError`.
  def top : T
    top { raise IndexError.new }
  end

  # Requires `0 <= i < size`, `0 <= j < size`.
  private def compare(i : Int32, j : Int32)
    x, y = @heap.unsafe_fetch(i), @heap.unsafe_fetch(j)
    if @compare_proc
      v = @compare_proc.not_nil!.call(x, y)
      raise ArgumentError.new("Comparison of #{x} and #{y} failed") if v.nil?
      v > 0
    else
      x > y
    end
  end

  # Adds *object* to the heap and returns `self`.
  def add(object : T) : self
    @heap << object
    i = size - 1
    parent = i.pred // 2
    while i > 0 && compare(parent, i)
      @heap.swap(parent, i)
      i, parent = parent, parent.pred // 2
    end
    self
  end

  # :ditto:
  def <<(object : T) : self
    add(object)
  end

  # Removes the lowest value from `self` and returns the removed value.
  # If the array is empty, the given block is called.
  def pop(&block)
    case size
    when 0
      yield
    when 1
      @heap.pop
    else
      value = @heap.unsafe_fetch(0)
      @heap[0] = @heap.pop
      i = 0
      loop do
        left, right = i * 2 + 1, i * 2 + 2
        j = if right < size && compare(i, right)
              compare(left, right) ? right : left
            elsif left < size && compare(i, left)
              left
            else
              break
            end
        @heap.swap(i, j)
        i = j
      end
      value
    end
  end

  # Like `#pop`, but returns `nil` if `self` is empty.
  def pop? : T?
    pop { nil }
  end

  # Removes the lowest value from `self` and returns the removed value.
  # Raises `IndexError` if heap is of 0 size.
  def pop : T
    pop { raise IndexError.new }
  end

  # Removes the last *n* values from `self` ahd returns the removed values.
  def pop(n : Int) : Array(T)
    raise ArgumentError.new unless n >= 0
    n = Math.min(n, size)
    Array.new(n) { pop }
  end

  # Yields each element of the heap, and returns `nil`.
  def each(&) : Nil
    @heap.each { |elem| yield elem }
  end

  # Returns an iterator for each element of the heap.
  def each
    @heap.each
  end

  # Returns a new array with all elements sorted.
  #
  # ```
  # a = BinaryHeap.new [3, 1, 2]
  # a.sort # => [1, 2, 3]
  # b = BinaryHeap.new [3, 1, 2] { |a, b| b <=> a }
  # b.sort # => [3, 2, 1]
  # ```
  def sort : Array(T)
    if @compare_proc
      @heap.sort { |a, b| @compare_proc.not_nil!.call(a, b) }
    else
      @heap.sort
    end
  end

  # Returns the elements as an Array.
  #
  # ```
  # BinaryHeap{3, 1, 2}.to_a # => [1, 3, 2]
  # ```
  def to_a : Array(T)
    @heap.dup
  end

  # Writes a string representation of the heap to `io`.
  #
  # ```
  # BinaryHeap{1, 2}.to_s # => "BinaryHeap{1, 2}"
  # ```
  def to_s(io : IO) : Nil
    io << "BinaryHeap{"
    # TODO: use join
    each_with_index do |x, i|
      io << ", " if i > 0
      io << x
    end
    io << '}'
  end

  # Writes a string representation of the heap to `io`.
  #
  # ```
  # BinaryHeap{1, 2}.inspect # => "BinaryHeap{1, 2}"
  # ```
  def inspect(io : IO) : Nil
    to_s(io)
  end
end

# require "../graph"
# require "./graph/edge"
struct WeightedEdge(T)
  include Comparable(WeightedEdge(T))

  property to : Int32, cost : T

  def initialize(@to, @cost : T)
  end

  def <=>(other : WeightedEdge(T))
    {cost, to} <=> {other.cost, other.to}
  end

  def to_s(io) : Nil
    io << '(' << to << ", " << cost << ')'
  end

  def inspect(io) : Nil
    io << "->" << to << '(' << cost << ')'
  end
end

struct WeightedEdge2(T)
  include Comparable(WeightedEdge2(T))

  property from : Int32, to : Int32, cost : T

  def initialize(@from, @to, @cost : T)
  end

  def initialize(@from, edge : WeightedEdge(T))
    @to, @cost = edge.to, edge.cost
  end

  def <=>(other : WeightedEdge2(T))
    {cost, from, to} <=> {other.cost, other.from, other.to}
  end

  def reverse : self
    WeightedEdge2(T).new(to, from, cost)
  end

  def sort : self
    WeightedEdge2(T).new(*{to, from}.minmax, cost)
  end

  def to_s(io) : Nil
    io << '(' << from << ", " << to << ", " << cost << ')'
  end

  def inspect(io) : Nil
    io << from << "->" << to << '(' << cost << ')'
  end
end

struct UnweightedEdge
  property to : Int32

  def initialize(@to)
  end

  def initialize(@to, cost)
  end

  def cost : Int32
    1
  end

  def to_s(io) : Nil
    io << to
  end

  def inspect(io) : Nil
    io << "->" << to
  end
end

struct UnweightedEdge2
  property from : Int32, to : Int32

  def initialize(@from, @to)
  end

  def initialize(@from, @to, cost)
  end

  def initialize(@from, edge : UnweightedEdge)
    @to = edge.to
  end

  def cost : Int32
    1
  end

  def reverse : self
    UnweightedEdge2.new(to, from)
  end

  def sort : self
    UnweightedEdge2.new(*{to, from}.minmax)
  end

  def to_s(io) : Nil
    io << '(' << from << ", " << to << ')'
  end

  def inspect(io) : Nil
    io << from << "->" << to
  end
end

module Graph(Edge, Edge2)
  include Enumerable(Edge2)

  getter graph : Array(Array(Edge))

  def initialize(size : Int)
    @graph = Array(Array(Edge)).new(size) { [] of Edge }
  end

  def initialize(size : Int, edges : Enumerable)
    initialize(size)
    add_edges(edges)
  end

  # Add *edge*.
  abstract def <<(edge : Edge2)

  # :ditto:
  def <<(edge : Tuple) : self
    self << Edge2.new(*edge)
  end

  def add_edges(edges : Enumerable) : self
    edges.each { |edge| self << edge }
    self
  end

  delegate size, :[], to: @graph

  # Yields each edge of the graph, ans returns `nil`.
  def each(&) : Nil
    (0...size).each do |v|
      graph[v].each do |edge|
        yield Edge2.new(v, edge)
      end
    end
  end

  def each_child(vertex : Int, parent, &block) : Nil
    graph[vertex].each do |edge|
      yield edge if edge.to != parent
    end
  end

  def each_child(vertex : Int, parent)
    graph[vertex].each.reject(&.to.== parent)
  end

  def reverse : self
    if self.class.directed?
      each_with_object(self.class.new(size)) do |edge, reversed|
        reversed << edge.reverse
      end
    else
      dup
    end
  end

  def to_undirected : self
    if self.class.directed?
      each_with_object(self.class.new(size)) do |edge, graph|
        graph << edge << edge.reverse
      end
    else
      dup
    end
  end

  def to_s(io : IO) : Nil
    io << '['
    join(", ", io) do |edge, io|
      edge.inspect io
    end
    io << ']'
  end

  def inspect(io : IO) : Nil
    io << "[\n"
    graph.each do |edges|
      io << "  " << edges << ",\n"
    end
    io << ']'
  end
end

class DiGraph(T)
  include Graph(WeightedEdge(T), WeightedEdge2(T))

  def self.weighted?
    true
  end

  def self.directed?
    true
  end

  def initialize(size : Int)
    super
  end

  def initialize(size : Int, edges : Enumerable(WeightedEdge2(T)))
    super
  end

  def initialize(size : Int, edges : Enumerable({Int32, Int32, T}))
    super
  end

  def <<(edge : WeightedEdge2(T)) : self
    raise IndexError.new unless 0 <= edge.from < size && 0 <= edge.to < size
    @graph[edge.from] << WeightedEdge.new(edge.to, edge.cost)
    self
  end
end

class UnGraph(T)
  include Graph(WeightedEdge(T), WeightedEdge2(T))

  def self.weighted?
    true
  end

  def self.directed?
    false
  end

  def initialize(size : Int)
    super
  end

  def initialize(size : Int, edges : Enumerable(WeightedEdge2(T)))
    super
  end

  def initialize(size : Int, edges : Enumerable({Int32, Int32, T}))
    super
  end

  def <<(edge : WeightedEdge2(T)) : self
    raise IndexError.new unless 0 <= edge.from < size && 0 <= edge.to < size
    @graph[edge.from] << WeightedEdge.new(edge.to, edge.cost)
    @graph[edge.to] << WeightedEdge.new(edge.from, edge.cost)
    self
  end
end

class UnweightedDiGraph
  include Graph(UnweightedEdge, UnweightedEdge2)

  def self.weighted?
    false
  end

  def self.directed?
    true
  end

  def initialize(size : Int)
    super
  end

  def initialize(size : Int, edges : Enumerable)
    super
  end

  def <<(edge : UnweightedEdge2) : self
    raise IndexError.new unless 0 <= edge.from < size && 0 <= edge.to < size
    @graph[edge.from] << UnweightedEdge.new(edge.to)
    self
  end
end

class UnweightedUnGraph
  include Graph(UnweightedEdge, UnweightedEdge2)

  def self.weighted?
    false
  end

  def self.directed?
    false
  end

  def initialize(size : Int)
    super
  end

  def initialize(size : Int, edges : Enumerable)
    super
  end

  def <<(edge : UnweightedEdge2) : self
    raise IndexError.new unless 0 <= edge.from < size && 0 <= edge.to < size
    @graph[edge.from] << UnweightedEdge.new(edge.to)
    @graph[edge.to] << UnweightedEdge.new(edge.from)
    self
  end
end

module Graph(Edge, Edge2)
  # Returns the array of distance of each node from *start* or `nil`.
  def dijkstra(start : Int)
    raise ArgumentError.new unless 0 <= start < size
    que = BinaryHeap({Int32, typeof(first.cost)}).new { |(v1, d1), (v2, d2)| d1 <=> d2 }
    que << {start, typeof(first.cost).zero}
    dist = Array(typeof(first.cost)?).new(size, nil)
    dist[start] = typeof(first.cost).zero

    until que.empty?
      v, d = que.pop
      next if dist[v].try { |dist_v| dist_v < d }
      current_dist = dist[v].not_nil!
      graph[v].each do |edge|
        next_dist = current_dist + edge.cost
        if dist[edge.to].nil? || dist[edge.to].not_nil! > next_dist
          dist[edge.to] = next_dist
          que << {edge.to, next_dist}
        end
      end
    end
    dist
  end

  # Returns the array of distance of each node from *start*.
  def dijkstra!(start : Int)
    dijkstra(start).map(&.not_nil!)
  end

  # Returns the distance of *start* to *goal* or `nil`.
  def dijkstra(start : Int, goal : Int)
    raise ArgumentError.new unless 0 <= start < size && 0 <= goal < size
    que = BinaryHeap({Int32, typeof(first.cost)}).new { |(v1, d1), (v2, d2)| d1 <=> d2 }
    que << {start, typeof(first.cost).zero}
    dist = Array(typeof(first.cost)?).new(size, nil)
    dist[start] = typeof(first.cost).zero

    until que.empty?
      v, d = que.pop
      return d if v == goal
      next if dist[v].try { |dist_v| dist_v < d }
      current_dist = dist[v].not_nil!
      graph[v].each do |edge|
        next_dist = current_dist + edge.cost
        if dist[edge.to].nil? || dist[edge.to].not_nil! > next_dist
          dist[edge.to] = next_dist
          que << {edge.to, next_dist}
        end
      end
    end
  end

  # Returns the distance of *start* to *goal*.
  def dijkstra!(start : Int, goal : Int)
    dijkstra(start, goal).not_nil!
  end

  def dijkstra_with_prev(start : Int)
    raise ArgumentError.new unless 0 <= start < size
    que = BinaryHeap({Int32, typeof(first.cost)}).new { |(v1, d1), (v2, d2)| d1 <=> d2 }
    que << {start, typeof(first.cost).zero}
    dist = Array(typeof(first.cost)?).new(size, nil)
    dist[start] = typeof(first.cost).zero
    prev = Array(Int32?).new(size, nil)

    until que.empty?
      v, d = que.pop
      next if dist[v].try { |dist_v| dist_v < d }
      current_dist = dist[v].not_nil!
      graph[v].each do |edge|
        next_dist = current_dist + edge.cost
        if dist[edge.to].nil? || dist[edge.to].not_nil! > next_dist
          dist[edge.to] = next_dist
          prev[edge.to] = v
          que << {edge.to, next_dist}
        end
      end
    end
    {dist, prev}
  end

  def dijkstra_with_path(start : Int, goal : Int)
    dist, prev = dijkstra_with_prev(start)
    if d = dist[goal]
      {d, Graph.restore_path(prev, goal)}
    end
  end

  def self.restore_path(prev : Array(Int32?), v : Int) : Array(Int32)
    v = v.to_i
    path = [v]
    while v = prev[v]
      path << v
    end
    path.reverse
  end
end
Back to top page