結果

問題 No.13 囲みたい!
ユーザー 👑 rin204rin204
提出日時 2022-07-04 14:39:04
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 136 ms / 5,000 ms
コード長 1,833 bytes
コンパイル時間 437 ms
コンパイル使用メモリ 86,912 KB
実行使用メモリ 76,644 KB
最終ジャッジ日時 2023-08-20 21:43:47
合計ジャッジ時間 2,857 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 74 ms
71,392 KB
testcase_01 AC 74 ms
71,268 KB
testcase_02 AC 74 ms
71,396 KB
testcase_03 AC 136 ms
76,384 KB
testcase_04 AC 87 ms
76,612 KB
testcase_05 AC 89 ms
76,644 KB
testcase_06 AC 97 ms
76,612 KB
testcase_07 AC 97 ms
76,544 KB
testcase_08 AC 85 ms
76,248 KB
testcase_09 AC 85 ms
76,244 KB
testcase_10 AC 80 ms
76,068 KB
testcase_11 AC 83 ms
76,400 KB
testcase_12 AC 75 ms
71,312 KB
testcase_13 AC 84 ms
76,468 KB
testcase_14 AC 80 ms
76,072 KB
testcase_15 AC 78 ms
71,144 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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())

w, h = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(h)]
f = lambda i, j:i * w + j
UF = UnionFind(h * w)
for i in range(h):
    for j in range(w - 1):
        if A[i][j] == A[i][j + 1]:
            f1 = f(i, j)
            f2 = f(i, j + 1)
            UF.union(f1, f2)
for i in range(h - 1):
    for j in range(w):
        if A[i][j] == A[i + 1][j]:
            f1 = f(i, j)
            f2 = f(i + 1, j)
            if UF.same(f1, f2):
                print("possible")
                exit()
            UF.union(f1, f2)
print("impossible")
0