結果
| 問題 |
No.1605 Matrix Shape
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-07-16 22:25:33 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 460 ms / 2,000 ms |
| コード長 | 2,217 bytes |
| コンパイル時間 | 172 ms |
| コンパイル使用メモリ | 82,304 KB |
| 実行使用メモリ | 106,400 KB |
| 最終ジャッジ日時 | 2024-07-06 09:51:47 |
| 合計ジャッジ時間 | 8,269 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 34 |
ソースコード
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
self.group = 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
self.group -= 1
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 self.group
def all_group_members(self):
dic = {r:[] for r in self.roots()}
for i in range(self.n):
dic[self.find(i)].append(i)
return dic
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n = int(input())
max_ = 2 * 10 ** 5
UF = UnionFind(max_)
edges = [[] for _ in range(max_)]
in_cnt = [0] * max_
out_cnt = [0] * max_
for _ in range(n):
h, w = map(int, input().split())
h -= 1
w -= 1
UF.union(h, w)
edges[h].append(w)
in_cnt[h] += 1
out_cnt[w] += 1
for i, o in enumerate(out_cnt):
if o != 0:
break
s = i
for j, o in enumerate(out_cnt):
if o != 0:
if not UF.same(s, j):
print(0)
exit()
s = -1
g = -1
for j, (i, o) in enumerate(zip(in_cnt, out_cnt)):
if i == o:
continue
if i == o + 1:
if s == -1:
s = j
else:
print(0)
exit()
elif i + 1 == o:
if g == -1:
g = j
else:
print(0)
exit()
else:
print(0)
exit()
if s == g == -1:
ans = 0
for e in edges:
if e: ans += 1
print(ans)
else:
print(1)