結果
問題 | No.1605 Matrix Shape |
ユーザー |
![]() |
提出日時 | 2023-04-17 11:59:33 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 603 ms / 2,000 ms |
コード長 | 2,858 bytes |
コンパイル時間 | 195 ms |
コンパイル使用メモリ | 82,412 KB |
実行使用メモリ | 117,408 KB |
最終ジャッジ日時 | 2024-10-12 13:32:01 |
合計ジャッジ時間 | 12,334 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 34 |
ソースコード
from math import sqrt,sin,cos,tan,ceil,radians,floor,gcd,exp,log,log10,log2,factorial,fsumfrom heapq import heapify, heappop, heappushfrom bisect import bisect_left, bisect_rightfrom copy import deepcopyimport copyimport randomfrom collections import deque,Counter,defaultdictfrom itertools import permutations,combinationsfrom decimal import Decimal,ROUND_HALF_UP#tmp = Decimal(mid).quantize(Decimal('0'), rounding=ROUND_HALF_UP)from functools import lru_cache, reduce#@lru_cache(maxsize=None)from operator import add,sub,mul,xor,and_,or_,itemgetterINF = 10**18mod1 = 10**9+7mod2 = 998244353#DecimalならPython#再帰ならPython!!!!!!!!!!!!!!!!!!!!!!!!!!class UnionFind():def __init__(self, n):self.n = nself.parents = [-1] * n#親だけself.edge = [0]*ndef find(self, x):if self.parents[x] < 0:return xelse: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 self.parents[x] > self.parents[y]:x, y = y, xself.edge[x] += 1if x == y:returnself.parents[x] += self.parents[y]self.edge[x] += self.edge[y]self.parents[y] = xdef 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_membersdef __str__(self):return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())'''グラフっぽく考えられそう最初と終わりさえ決めれば間は関係ない全部を通って終わりまでたどりつけるか?という問題sccして1個なら全部行ける1個じゃなくて、パスがあったらその組はいける入次数0から始めるそこから全部通れるかサイクルはSCCで対処可能'''N = int(input())lim = 2*(10**5)+1uf = UnionFind(lim)memo = defaultdict(int)for i in range(N):h,w = map(int, input().split())memo[h-1] += 1memo[w-1] -= 1uf.union(h,w)M = len(memo.keys())if uf.group_count() != lim-M+1:print(0)exit()ls = list(memo.values())ls.sort()if ls[0] == ls[-1] == 0:print(M)elif -ls[0] == ls[-1] == 1 and ls.count(0) == len(ls)-2:print(1)else:print(0)