https://www.acmicpc.net/problem/21608
import sys
read = sys.stdin.readline
n = int(read())
orders = []
like = [set() for _ in range(n**2+1)]
for _ in range(n**2):
num, a,b,c,d = map(int, read().split())
orders.append(num)
like[num] = set([a,b,c,d])
board = [[0]*(n+1) for _ in range(n+1)]
dy, dx = [1,-1,0,0], [0,0,1,-1]
# 순서대로
for num in orders:
# 최대 위치 찾기
max_like, max_empty = -1, -1
my, mx = 100, 100
for cy in range(1, n+1):
for cx in range(1, n+1):
if board[cy][cx] != 0:
continue
# 좋 개수, 빈 개수 세기
like_count, empty_count = 0, 0
for d in range(4):
ny, nx = cy+dy[d], cx+dx[d]
if 1<=ny<=n and 1<=nx<=n:
if board[ny][nx] in like[num]:
like_count += 1
elif board[ny][nx] == 0:
empty_count += 1
# 최대이면 갱신
if max_like < like_count:
max_like, max_empty = like_count, empty_count
my, mx = cy, cx
elif max_like == like_count:
if max_empty < empty_count:
max_like, max_empty = like_count, empty_count
my, mx = cy, cx
board[my][mx] = num
# 만족도 구하기
answer = 0
for cy in range(1, n+1):
for cx in range(1, n+1):
num = board[cy][cx]
# 좋 개수, 빈 개수 세기
like_count = 0
for d in range(4):
ny, nx = cy+dy[d], cx+dx[d]
if 1<=ny<=n and 1<=nx<=n:
if board[ny][nx] in like[num]:
like_count += 1
if like_count > 0:
answer += 10 ** (like_count-1)
print(answer)