結果

問題 No.13 囲みたい!
ユーザー roarisroaris
提出日時 2019-08-26 17:08:24
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 73 ms / 5,000 ms
コード長 1,350 bytes
コンパイル時間 175 ms
コンパイル使用メモリ 82,432 KB
実行使用メモリ 72,320 KB
最終ジャッジ日時 2024-04-25 08:47:23
合計ジャッジ時間 1,789 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 44 ms
52,096 KB
testcase_01 AC 43 ms
52,352 KB
testcase_02 AC 42 ms
52,352 KB
testcase_03 AC 66 ms
70,528 KB
testcase_04 AC 46 ms
60,800 KB
testcase_05 AC 68 ms
70,144 KB
testcase_06 AC 73 ms
71,680 KB
testcase_07 AC 71 ms
72,320 KB
testcase_08 AC 56 ms
64,512 KB
testcase_09 AC 56 ms
64,640 KB
testcase_10 AC 48 ms
61,312 KB
testcase_11 AC 53 ms
63,488 KB
testcase_12 AC 47 ms
59,648 KB
testcase_13 AC 54 ms
62,848 KB
testcase_14 AC 52 ms
62,592 KB
testcase_15 AC 44 ms
52,864 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class Unionfind:
    def __init__(self, N):
        self.par = [-1] * N
        self.rank = [1] * N
        
    def root(self, x):
        if self.par[x] < 0:
            return x
        
        self.par[x] = self.root(self.par[x])
        return self.par[x]
    
    def unite(self, x, y):
        rx, ry = self.root(x), self.root(y)
        
        if rx != ry:
            if self.rank[rx] >= self.rank[ry]:
                self.par[rx] += self.par[ry]
                self.par[ry] = rx
                
                if self.rank[rx] == self.rank[ry]:
                    self.rank[rx] += 1
            else:
                self.par[ry] += self.par[rx]
                self.par[rx] = ry
    
    def is_same(self, x, y):
        return self.root(x) == self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]

W, H = map(int, input().split())
M = [list(map(int, input().split())) for _ in range(H)]
adj_list = [[] for _ in range(W*H)]
uf = Unionfind(H*W)

for i in range(H):
    for j in range(W):
        for ni, nj in [(i+1, j), (i, j+1)]:
            if 0 <= ni < H and 0 <= nj < W and M[i][j] == M[ni][nj]:
                if uf.is_same(i*W+j, ni*W+nj):
                    print('possible')
                    exit()
                else:
                    uf.unite(i*W+j, ni*W+nj)
    
print('impossible')
0