結果

問題 No.556 仁義なきサルたち
ユーザー niodachi1niodachi1
提出日時 2019-10-16 09:48:49
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 58 ms / 2,000 ms
コード長 1,109 bytes
コンパイル時間 1,067 ms
コンパイル使用メモリ 10,928 KB
実行使用メモリ 9,424 KB
最終ジャッジ日時 2023-09-02 09:59:49
合計ジャッジ時間 2,270 ms
ジャッジサーバーID
(参考情報)
judge16 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 17 ms
8,320 KB
testcase_01 AC 17 ms
8,236 KB
testcase_02 AC 16 ms
8,216 KB
testcase_03 AC 16 ms
8,240 KB
testcase_04 AC 16 ms
8,396 KB
testcase_05 AC 17 ms
8,304 KB
testcase_06 AC 17 ms
8,296 KB
testcase_07 AC 17 ms
8,332 KB
testcase_08 AC 18 ms
8,336 KB
testcase_09 AC 18 ms
8,400 KB
testcase_10 AC 21 ms
8,056 KB
testcase_11 AC 20 ms
8,032 KB
testcase_12 AC 20 ms
8,096 KB
testcase_13 AC 21 ms
8,460 KB
testcase_14 AC 31 ms
8,768 KB
testcase_15 AC 35 ms
8,724 KB
testcase_16 AC 34 ms
8,700 KB
testcase_17 AC 43 ms
8,932 KB
testcase_18 AC 58 ms
9,352 KB
testcase_19 AC 56 ms
9,128 KB
testcase_20 AC 58 ms
9,368 KB
testcase_21 AC 58 ms
9,424 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(10**6)

class UnionFind():
	def __init__(self, n):
		self.size = n
		self.root = [-1 for _ in range(n+1)]
		self.rnk = [0 for _ in range(n+1)]

	def findRoot(self, a):
		if self.root[a] < 0:
			return a
		else:
			return self.findRoot(self.root[a])

	def uniteTree(self, a, b):
		a = self.findRoot(a)
		b = self.findRoot(b)
		if a == b:
			return

		a_elemets = self.root[a] * (-1)
		b_elemets = self.root[b] * (-1)

		if a_elemets == b_elemets:
			sup = min(a,b)
			inf = max(a,b)
		elif a_elemets > b_elemets:
			sup = a
			inf = b
		else:
			sup = b
			inf = a

		self.root[sup] += self.root[inf]
		self.root[inf] = sup



	def judgeTree(self, a, b):
		return self.findRoot(a) == self.findRoot(b)

	def count(self, a):
		return self.rnk[self.findRoot(a)] * (-1)


N, M = map(int, input().split())
A = []
B = []

for i in range(M):
	a_tmp, b_tmp = map(int, input().split())
	A.append(a_tmp)
	B.append(b_tmp)

monkey = UnionFind(N)

for i in range(M):
	monkey.uniteTree(A[i], B[i])

for i in range(1,N+1):
	if monkey.root[i] < 0:
		print(i)
	else:
		print(monkey.findRoot(i))
0