結果
問題 |
No.1576 織姫と彦星
|
ユーザー |
|
提出日時 | 2021-10-31 15:50:46 |
言語 | Ruby (3.4.1) |
結果 |
AC
|
実行時間 | 271 ms / 2,000 ms |
コード長 | 1,135 bytes |
コンパイル時間 | 518 ms |
コンパイル使用メモリ | 7,296 KB |
実行使用メモリ | 12,288 KB |
最終ジャッジ日時 | 2024-10-09 00:15:09 |
合計ジャッジ時間 | 12,043 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 5 |
other | AC * 54 |
コンパイルメッセージ
Main.rb:65: warning: ambiguous first argument; put parentheses or a space even after `-' operator Syntax OK
ソースコード
N = gets.to_i s, e = gets.split(" ").map{|s| s.to_i} stone = gets.split(" ").map{|s| s.to_i} class UnionFind def initialize(n) @par = 0.upto(n-1).to_a @rank = Array.new(n, 0) end def unite(x, y) x = find(x) y = find(y) return if x == y if @rank[x] < @rank[y] then @par[x] = y else @par[y] = x @rank[x] += 1 if @rank[x] == @rank[y] end end def same?(x, y) find(x) == find(y) end private def find(x) if @par[x] == x then x else @par[x] = find(@par[x]) end end end stone = [s] + stone + [e] def getHaming(n) bit = 1 haming = [n] 32.times { haming << (n ^ bit) bit <<= 1 } haming end uf = UnionFind.new(N+2) v = Array.new(N+2) {Array.new} stone.each_with_index {|x, i| haming = getHaming(x) (i+1).upto(N+1) {|j| if haming.include?(stone[j]) then uf.unite(i, j) v[i] << j v[j] << i end } } if not uf.same?(0, N+1) then puts -1 else d = Array.new(N+2, Float::INFINITY) d[0] = 0 q = [[0, 0]] while q.length > 0 do cv, c = q.shift v[cv].each {|nv| if d[nv] > c + 1 then d[nv] = c + 1 q << [nv, c + 1] end } end puts d[N+1]-1 end