반응형
문제 링크: https://www.acmicpc.net/problem/16234
16234번: 인구 이동
N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모
www.acmicpc.net
<문제 풀이> BFS
BFS를 이용해서 두 인구 차이가 L 이상 R 이하를 만족하는 연결 요소를 구하면 되는데, 이때 지나온 좌표, 현재까지 인구의 합을 저장해 두고 queue가 비면 인구 이동을 진행하면 된다.
현재까지의 좌표의 개수가 2개 이상일 때 두 그룹 이상이 생기는 거니깐 이 경우에만 인구 이동을 진행한다.
-> bfs가 bool을 return 하도록 하고 인구 이동이 한 번 이상 진행한 경우 true
-> bfs가 true면 다시 bfs를 호출
<C++ 소스 코드>
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
|
#include<iostream>
#include<utility>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define X first
#define Y second
const int dx[4] = { 0, 0, 1, -1 };
const int dy[4] = { 1, -1, 0, 0 };
int N, L, R;
int A[50][50];
bool visited[50][50];
bool bfs() {
bool ret = false;
fill(&visited[0][0], &visited[49][50], 0);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (visited[i][j]) continue;
queue<pair<int, int > > Q;
vector<pair<int, int> > trace;
int tot = A[i][j];
Q.push({ i, j });
trace.push_back({ i, j }); //지나온 좌표 저장
visited[i][j] = true;
while (!Q.empty()) {
auto cur = Q.front(); Q.pop();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || ny < 0 || nx >= N || ny >= N)continue;
if (visited[nx][ny])continue;
if (A[nx][ny] == -1)continue;
int diff = abs(A[nx][ny] - A[cur.X][cur.Y]);
if (diff< L || diff > R) continue;
tot += A[nx][ny]; // 인구이동이 가능하면
Q.push({ nx, ny });
visited[nx][ny] = true;
trace.push_back({ nx, ny });
}
}
int trace_size = trace.size();
if (trace_size >= 2) {
ret = true;
for (auto& e : trace) {
A[e.X][e.Y] = tot / trace_size;
}
}
}
}
return ret;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> N >> L >> R;
fill(&A[0][0], &A[49][50], -1);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin>>A[i][j];
}
}
int ans = 0;
while (bfs()) {
ans++;
}
cout << ans;
return 0;
}
|
cs |
반응형
'알고리즘 문제풀이 > 백준' 카테고리의 다른 글
[백준 3055번] 탈출 (0) | 2022.03.13 |
---|---|
[백준 16946번] 벽 부수고 이동하기 4 (0) | 2022.03.11 |
[백준 13460번] 구슬 탈출 2 (0) | 2022.02.10 |
[백준 16973번] 직사각형 탈출 (0) | 2022.01.31 |
[백준 16932번] 모양 만들기 (0) | 2022.01.31 |