結果

問題 No.1605 Matrix Shape
ユーザー ntuda
提出日時 2021-08-13 22:00:30
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 647 ms / 2,000 ms
コード長 1,838 bytes
コンパイル時間 347 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 149,696 KB
最終ジャッジ日時 2024-10-03 18:51:50
合計ジャッジ時間 11,723 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 34
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

import sys
N = int(input())
HW = [list(map(int,input().split())) for _ in range(N)]
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):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
dic = {}
i = 0
for hw in HW:
h,w = hw
if not(h in dic):
dic[h] = i
i += 1
if not(w in dic):
dic[w] = i
i += 1
n = i
uf = UnionFind(n)
for hw in HW:
h,w = hw
uf.union(dic[h],dic[w])
if uf.group_count() != 1:
print(0)
sys.exit()
MAX = 2*10**5+1
H = [[] for _ in range(MAX)]
W = [[] for _ in range(MAX)]
for hw in HW:
h,w = hw
H[h].append(w)
W[w].append(h)
cnt = 0
for i in range(MAX):
cnt += abs(len(H[i]) - len(W[i]))
if cnt > 2:
print(0)
sys.exit()
if cnt == 0:
print(n)
else:
print(1)
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0