結果

問題 No.1565 Union
ユーザー O2MTO2MT
提出日時 2021-07-26 16:49:16
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,666 bytes
コンパイル時間 890 ms
コンパイル使用メモリ 87,136 KB
実行使用メモリ 97,232 KB
最終ジャッジ日時 2023-09-29 13:32:42
合計ジャッジ時間 7,205 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 76 ms
71,644 KB
testcase_01 AC 74 ms
71,728 KB
testcase_02 AC 75 ms
71,496 KB
testcase_03 AC 74 ms
71,640 KB
testcase_04 AC 72 ms
71,576 KB
testcase_05 AC 74 ms
71,756 KB
testcase_06 AC 75 ms
71,636 KB
testcase_07 AC 91 ms
71,596 KB
testcase_08 AC 74 ms
71,440 KB
testcase_09 AC 76 ms
71,756 KB
testcase_10 AC 199 ms
83,668 KB
testcase_11 AC 371 ms
97,232 KB
testcase_12 AC 328 ms
88,528 KB
testcase_13 AC 247 ms
83,708 KB
testcase_14 AC 398 ms
93,148 KB
testcase_15 TLE -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque,defaultdict

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
 
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
 
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
 
        if x == y:
            return
 
        if self.parents[x] > self.parents[y]:
            x, y = y, x
 
        self.parents[x] += self.parents[y]
        self.parents[y] = x
 
    def size(self, x):
        return -self.parents[self.find(x)]
 
    def same(self, x, y):
        return self.find(x) == self.find(y)
 
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
 
    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]
 
    def group_count(self):
        return len(self.roots())
 
    def all_group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members

N,M = map(int,input().split())
l = [[] for _ in range(N)]
uf = UnionFind(N)

for _ in range(M):
  a,b = map(int,input().split())
  a -= 1
  b -= 1
  l[a].append(b)
  l[b].append(a)
  uf.union(a,b)

if not uf.same(0,N-1):
  print(-1)
  exit()
uf = False
INF = 10**18
visited = [INF]*N
que = deque([(0,0)])
while que:
  i,c = que.pop()
  for j in l[i]:
    if c+1 < visited[j]:
      que.append((j,c+1))
      visited[j] = c+1
ans = visited[N-1]

print(ans)







0