Skip to content

Commit 5978085

Browse files
committed
[BOJ] 인구 이동 / 골드 4 / 80분
https://www.acmicpc.net/problem/16234
1 parent 7e9a583 commit 5978085

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import sys
2+
from collections import deque
3+
4+
#1. 입력값 받기
5+
#2. 모든 배열을 돌며 인구이동 조건을 만족하는 나라가 있는지 확인. (1. 인접한 나라 2. 두 국가의 인구 차의 절댓값이 l이상 r이하)
6+
#3. 인구 이동조건을 만족하는 나라가 있으면 bfs로 그래프를 탐색하면서 나라의 개수와 인구의 총합을 구해서 새로운 인구를 구해준다.
7+
#4. visited 배열은 인구 이동날마다 초기화 해야 한다.
8+
9+
# 실제로 인구를 이동시키는 함수
10+
def movePopulation(i, j):
11+
global n, l, r
12+
global visited, arr
13+
14+
dx = [-1, 1, 0, 0]
15+
dy = [0, 0, -1, 1]
16+
17+
queue = deque([(i, j)])
18+
visited[i][j] = 1
19+
queue2 = deque([(i, j)])
20+
populationSum = arr[i][j]
21+
countrySum = 1
22+
23+
while queue:
24+
x, y = queue.popleft()
25+
26+
for d in range(4):
27+
row = x + dx[d]
28+
col = y + dy[d]
29+
30+
if 0 <= row < n and 0 <= col < n and visited[row][col] == 0 and l <= abs(arr[x][y] - arr[row][col]) <= r:
31+
visited[row][col] = 1
32+
countrySum += 1
33+
populationSum += arr[row][col]
34+
queue.append((row, col))
35+
queue2.append((row, col))
36+
37+
newPopulation = populationSum // countrySum
38+
39+
while queue2:
40+
x, y = queue2.popleft()
41+
arr[x][y] = newPopulation
42+
43+
# 인구 이동 조건을 만족하는 나라가 있는지 확인하는 함수
44+
def checkCountries():
45+
global ans
46+
47+
dx = [-1, 1, 0, 0]
48+
dy = [0, 0, -1, 1]
49+
50+
for i in range(n):
51+
for j in range(n):
52+
for k in range(4):
53+
row = i + dx[k]
54+
col = j + dy[k]
55+
if 0 <= row < n and 0 <= col < n and l <= abs(arr[i][j] - arr[row][col]) <= r:
56+
ans += 1
57+
return True
58+
59+
return False
60+
61+
62+
inp = sys.stdin.readline
63+
64+
n, l, r = map(int, inp().split())
65+
66+
arr = []
67+
visited = [[0] * n for _ in range(n)]
68+
69+
ans = 0
70+
71+
for i in range(n):
72+
arr.append(list(map(int, inp().split())))
73+
74+
while checkCountries():
75+
for i in range(n):
76+
for j in range(n):
77+
if visited[i][j] == 0:
78+
movePopulation(i, j)
79+
visited = [[0] * n for _ in range(n)]
80+
81+
print(ans)

0 commit comments

Comments
 (0)