Skip to content

Commit 436dfdf

Browse files
committed
[BOJ] 21608 상어 초등학교 (G5)
1 parent 3c848c5 commit 436dfdf

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

최어진/8주차/260222.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# 백준 21608번: 상어 초등학교 (3회차)
2+
3+
import sys
4+
5+
input = sys.stdin.readline
6+
7+
# N <= 20
8+
N = int(input())
9+
maps = [[False for _ in range(N)] for _ in range(N)]
10+
students = []
11+
favorites = {}
12+
for _ in range(N**2):
13+
student_num, *student_favorites = map(int, input().rstrip().split())
14+
students.append(student_num)
15+
favorites[student_num] = student_favorites
16+
17+
# 브루트포싱
18+
# 1. N**2명의 학생 자리를 정함 -> O(N^2)
19+
# 2. 각 학생마다 모든 가능한 자리를 검사 -> O(N^2)
20+
# 결론: O(N^4)
21+
22+
moves = [
23+
[0, 1],
24+
[0, -1],
25+
[1, 0],
26+
[-1, 0]
27+
]
28+
29+
def print_seats():
30+
for row in maps:
31+
print(row)
32+
print()
33+
34+
def is_in_board(r, c):
35+
return 0 <= r < N and 0 <= c < N
36+
37+
def get_nearest_favorites(r, c, favorites):
38+
cnt = 0
39+
for dr, dc in moves:
40+
if is_in_board(r + dr, c + dc) and maps[r + dr][c + dc]:
41+
if maps[r + dr][c + dc] in favorites: cnt += 1
42+
return cnt
43+
44+
def get_nearest_empty_seats(r, c):
45+
cnt = 0
46+
for dr, dc in moves:
47+
if is_in_board(r + dr, c + dc):
48+
if not maps[r + dr][c + dc]: cnt += 1
49+
return cnt
50+
51+
def check_new_seat(favorites):
52+
max_favorites = -1
53+
max_emptys = -1
54+
seats = [-1, -1]
55+
56+
for r in range(N):
57+
for c in range(N):
58+
if maps[r][c]: continue
59+
60+
nearest_favorites = get_nearest_favorites(r, c, favorites)
61+
nearest_emptys = get_nearest_empty_seats(r, c)
62+
63+
if nearest_favorites > max_favorites:
64+
# print(f'* 친한 친구가 {nearest_favorites}명으로 가장 많은 자리 -> {(r, c)}')
65+
max_favorites = nearest_favorites
66+
max_emptys = nearest_emptys
67+
seats = [r, c]
68+
elif nearest_favorites == max_favorites:
69+
if nearest_emptys > max_emptys:
70+
# print(f'* 빈 자리가 {nearest_emptys}개로 가장 많은 자리 -> {(r, c)}')
71+
max_emptys = nearest_emptys
72+
seats = [r, c]
73+
74+
return seats
75+
76+
def get_satisfying():
77+
sums = 0
78+
for r in range(N):
79+
for c in range(N):
80+
student_num = maps[r][c]
81+
student_favorites = favorites[student_num]
82+
score = get_nearest_favorites(r, c, student_favorites)
83+
84+
if score >= 4: sums += 1000
85+
elif score >= 3: sums += 100
86+
elif score >= 2: sums += 10
87+
elif score: sums += 1
88+
return sums
89+
90+
for num in students:
91+
student_favorites = favorites[num]
92+
# print(f'{num}번 학생: {set(student_favorites)}')
93+
r, c = check_new_seat(set(student_favorites))
94+
maps[r][c] = num
95+
# print_seats()
96+
97+
print(get_satisfying())

0 commit comments

Comments
 (0)