結果
| 問題 | No.13 囲みたい! | 
| コンテスト | |
| ユーザー |  ytft | 
| 提出日時 | 2022-11-03 00:06:27 | 
| 言語 | PyPy3 (7.3.15) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 103 ms / 5,000 ms | 
| コード長 | 1,329 bytes | 
| コンパイル時間 | 253 ms | 
| コンパイル使用メモリ | 82,232 KB | 
| 実行使用メモリ | 77,328 KB | 
| 最終ジャッジ日時 | 2024-07-17 11:48:24 | 
| 合計ジャッジ時間 | 2,201 ms | 
| ジャッジサーバーID (参考情報) | judge4 / judge5 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 16 | 
ソースコード
import sys
input=lambda:sys.stdin.readline().rstrip()
class unionFind:
    def __init__(self,N):
        self.N=N
        self.parent=[-1 for i in range(N)]
        self.size=[1 for i in range(N)]
    def find(self,x):
        path=[x]
        while self.parent[path[-1]]!=-1:
            path.append(self.parent[path[-1]])
        for i in path[:-1]:
            self.parent[i]=path[-1]
        return path[-1]
    def unite(self,x,y):
        roots=sorted([self.find(x),self.find(y)],key=lambda _:self.parent[_])
        if roots[0]!=roots[1]:
            self.parent[roots[0]]=roots[1]
            self.size[roots[1]]+=self.size[roots[0]]
W,H=map(int,input().split())
field=[list(map(lambda x:int(x)-1,input().split())) for i in range(H)]
u=unionFind(H*W)
islands=[set() for i in range(1000)]
connections=[0 for i in range(1000)]
count=[0 for i in range(1000)]
for i in range(H):
	for j in range(W):
		count[field[i][j]]+=1
		if j<W-1 and field[i][j]==field[i][j+1]:
			u.unite(i*W+j,i*W+j+1)
			connections[field[i][j]]+=1
		if i<H-1 and field[i][j]==field[i+1][j]:
			u.unite(i*W+j,i*W+j+W)
			connections[field[i][j]]+=1
for i in range(H):
	for j in range(W):
		islands[field[i][j]].add(u.find(i*W+j))
for i in range(1000):
	if count[i]-connections[i]-len(islands[i])<0:
		print('possible')
		sys.exit()
print('impossible')
            
            
            
        