[C++]백준 16234번 인구 이동
[C++]백준 16234번 인구 이동
📌문제 링크
https://www.acmicpc.net/problem/16234
📌문제 설명
입력으로 받은 N×N 크기의 인구 배열을 기반으로, 각 칸을 탐색하며 인접 국가 간의 인구 차이가 조건(L ≤ 차이 ≤ R)을 만족하면 국경을 열어 연합을 형성합니다. BFS를 통해 연합에 포함된 칸들의 인구 총합과 개수를 계산한 뒤, 새로운 인구값으로 갱신합니다. 이동이 발생하면 인구 정보를 업데이트하고, 이동이 더 이상 없을 때까지 이를 반복합니다. 최종적으로 인구 이동이 발생한 일수를 출력하며, 효율적인 시뮬레이션을 위해 방문 배열과 새로운 인구 배열을 초기화하며 진행합니다.
📌코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
bool visited[51][51];
int N, L, R, mp[51][51], answer, newMp[51][51];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void input() {
cin >> N >> L >> R;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
cin >> mp[i][j];
}
}
}
void init() {
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
visited[i][j] = false;
newMp[i][j] = mp[i][j];
}
}
}
void bfs(int x, int y) {
vector<pair<int, int>> united;
queue<pair<int, int>> q;
q.push({x, y});
united.push_back({x, y});
visited[x][y] = true;
int total = mp[x][y];
int count = 1;
while (!q.empty()) {
auto [cx, cy] = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (nx < 0 || nx >= N || ny < 0 || ny >= N || visited[nx][ny])
continue;
int diff = abs(mp[cx][cy] - mp[nx][ny]);
if (diff >= L && diff <= R) {
q.push({nx, ny});
united.push_back({nx, ny});
visited[nx][ny] = true;
total += mp[nx][ny];
count++;
}
}
}
if (count > 1) {
int newValue = total / count;
for (auto [ux, uy] : united) {
newMp[ux][uy] = newValue;
}
}
}
void solve() {
input();
answer = 0;
while (true) {
init();
bool moved = false;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j]) {
bfs(i, j);
}
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (mp[i][j] != newMp[i][j]) {
moved = true;
}
mp[i][j] = newMp[i][j];
}
}
if (!moved) {
break;
}
answer++;
}
cout << answer;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
This post is licensed under CC BY 4.0 by the author.