Skip to content

Instantly share code, notes, and snippets.

@whatalnk
Created April 11, 2016 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whatalnk/2cc2a59ea295485404e389da5707c4f3 to your computer and use it in GitHub Desktop.
Save whatalnk/2cc2a59ea295485404e389da5707c4f3 to your computer and use it in GitHub Desktop.
AtCoder ATC #002
r, c = gets.chomp.split(" ").map(&:to_i)
sx, sy = gets.chomp.split(" ").map(&:to_i)
gx, gy = gets.chomp.split(" ").map(&:to_i)
maize = []
r.times do
maize << gets.chomp.split("")
end
dist = Array.new(r).map{Array.new(c, -1)}
dist[sx-1][sy-1] = 0
queue = [[sx, sy]]
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
while !queue.empty?
x0, y0 = queue.shift
curr = dist[x0-1][y0-1]
direction.each do |dx, dy|
x1 = x0 + dx
y1 = y0 + dy
if (x1 > 1) and (x1 < r) and (y1 > 1) and (y1 < c) and (maize[x1-1][y1-1] == ".") and (dist[x1-1][y1-1] < 0) then
dist[x1-1][y1-1] = curr + 1
queue.push([x1, y1])
end
end
end
puts dist[gx-1][gy-1]
n, m, p = gets.chomp.split(" ").map(&:to_i)
def pow_mod(n, p, m)
if p == 0 then
return 1
elsif p.odd? then
return pow_mod(n, p-1, m) * n % m
else
t = pow_mod(n, p / 2, m)
return t * t % m
end
end
puts pow_mod(n, p, m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment