https://www.acmicpc.net/problem/16234
N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다.
오늘부터 인구 이동이 시작되는 날이다.
인구 이동은 하루 동안 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다.
- 국경선을 공유하는 두 나라의 인구 차이가 L명 이상, R명 이하라면, 두 나라가 공유하는 국경선을 오늘 하루 동안 연다.
- 위의 조건에 의해 열어야 하는 국경선이 모두 열렸다면, 인구 이동을 시작한다.
- 국경선이 열려있어 인접한 칸만을 이용해 이동할 수 있으면, 그 나라를 오늘 하루 동안은 연합이라고 한다.
- 연합을 이루고 있는 각 칸의 인구수는 (연합의 인구수) / (연합을 이루고 있는 칸의 개수)가 된다. 편의상 소수점은 버린다.
- 연합을 해체하고, 모든 국경선을 닫는다.
각 나라의 인구수가 주어졌을 때, 인구 이동이 며칠 동안 발생하는지 구하는 프로그램을 작성하시오.
2 20 50
50 30
20 40
첫째 줄에 N, L, R이 주어진다. (1 ≤ N ≤ 50, 1 ≤ L ≤ R ≤ 100)
둘째 줄부터 N개의 줄에 각 나라의 인구수가 주어진다. r행 c열에 주어지는 정수는 A[r][c]의 값이다. (0 ≤ A[r][c] ≤ 100)
인구 이동이 발생하는 일수가 2,000번 보다 작거나 같은 입력만 주어진다.
1
인구 이동이 며칠 동안 발생하는지 첫째 줄에 출력한다.
아이디어
- 인접한 두 국가의 인구 차이가 L 이상, R 이하인지 확인한다.
- 조건에 맞다면 국경을 개방하고, 연합을 형성한다.
- 연합은 여러 개가 생길 수 있다.
- 조건에 맞다면 연합을 만든다. → BFS
- 결과적으로 연합이 3개가 생겼다고 가정하면, 각 연합의 인구수를 그 연합의 평균값으로 바꾼다.
- 더 이상 국경이 열리지 않을 때까지 반복한다.
첫 번째 시도 - 실패
import java.io.*;
import java.util.*;
class Main {
static int N, L, R, day = 0;
static int[][] map;
static boolean[][] visited;
static int[] dr = {0, 1, 0, -1};
static int[] dc = {1, 0, -1, 0};
static boolean united = false;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
L = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
map = new int[N][N];
visited = new boolean[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
while (true) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j]) {
bfs(i, j);
}
}
}
if (!united) break;
visited = new boolean[N][N];
united = false;
day++;
}
System.out.println(day);
}
static void bfs(int r, int c) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{r, c});
visited[r][c] = true;
List<int[]> unities = new ArrayList<>();
int unity = 0;
int sum = 0;
while (!q.isEmpty()) {
int[] cur = q.poll();
int cr = cur[0];
int cc = cur[1];
for (int d = 0; d < 4; d++) {
int nr = cr + dr[d];
int nc = cc + dc[d];
if (nr < 0 || nc < 0 || nr >= N || nc >= N) continue;
if (visited[nr][nc]) continue;
int diff = Math.abs(map[nr][nc] - map[cr][cc]);
if (diff >= L && diff <= R) {
if (!united) {
united = true;
unities.add(new int[]{cr, cc});
sum += map[cr][cc];
unity++;
}
unities.add(new int[]{nr, nc});
sum += map[nr][nc];
unity++;
}
q.add(new int[]{nr, nc});
visited[nr][nc] = true;
}
}
if (united) {
int avg = sum / unity;
for (int[] u : unities) {
map[u[0]][u[1]] = avg;
}
}
}
}
- 왜 틀렸는지 생각해 보니, 한 연합이 생성되자마자 바로 인구 이동을 실행했다.
- 따라서 연합이 여러 개가 있을 경우, 다음 연합을 탐색할 때 이미 변경된 인구수를 기준으로 했을 것이다.
- 따라서 다음과 같이 코드를 변경했다.
두 번째 시도 - 실패
import java.io.*;
import java.util.*;
class Main {
static int N, L, R, day = 0;
static int[][] map, unitedMap;
static boolean[][] visited;
static int[] dr = {0, 1, 0, -1};
static int[] dc = {1, 0, -1, 0};
static boolean united = false;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
L = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
map = new int[N][N];
visited = new boolean[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
unitedMap = map;
while (true) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j]) {
bfs(i, j);
}
}
}
if (!united) break;
visited = new boolean[N][N];
map = unitedMap;
united = false;
day++;
}
System.out.println(day);
}
static void bfs(int r, int c) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{r, c});
visited[r][c] = true;
List<int[]> unities = new ArrayList<>();
int unity = 0;
int sum = 0;
while (!q.isEmpty()) {
int[] cur = q.poll();
int cr = cur[0];
int cc = cur[1];
for (int d = 0; d < 4; d++) {
int nr = cr + dr[d];
int nc = cc + dc[d];
if (nr < 0 || nc < 0 || nr >= N || nc >= N) continue;
if (visited[nr][nc]) continue;
int diff = Math.abs(map[nr][nc] - map[cr][cc]);
if (diff >= L && diff <= R) {
if (!united) {
united = true;
unities.add(new int[]{cr, cc});
sum += map[cr][cc];
unity++;
}
unities.add(new int[]{nr, nc});
sum += map[nr][nc];
unity++;
}
q.add(new int[]{nr, nc});
visited[nr][nc] = true;
}
}
if (united) {
int avg = sum / unity;
for (int[] u : unities) {
unitedMap[u[0]][u[1]] = avg;
}
}
}
}
- 맵을 복사한 임시 맵을 만들었다.
- 각 연합마다 인구 이동을 한 값을 임시 맵에 저장하고, 모든 연합을 탐색했다면 임시 맵을 기존 맵으로 치환시켰다.
- 내 예상과는 달리 아직 해결되지 않았다.
- 직접 손으로 BFS 과정을 그려보니 짐작되는 게 있다.
- 큐에 (0, 1)과 (1, 0)이 들어있을 때, (1, 1)은 (0, 1)과는 비교를 하지만, (1, 0)과는 visited 처리 때문에 비교하지 않는다.
- 즉, 국경 검사 하나를 빼먹은 것이다.
- 이 사실을 바탕으로 수정해 보자.
세 번째 시도 - 성공
import java.io.*;
import java.util.*;
class Main {
static int N, L, R, day = 0;
static int[][] map, unitedMap;
static boolean[][] visited;
static int[] dr = {0, 1, 0, -1};
static int[] dc = {1, 0, -1, 0};
static boolean united = false;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
L = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
map = new int[N][N];
visited = new boolean[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
unitedMap = map;
while (true) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j]) {
bfs(i, j);
}
}
}
if (!united) break;
visited = new boolean[N][N];
map = unitedMap;
united = false;
day++;
}
System.out.println(day);
}
static void bfs(int r, int c) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{r, c});
visited[r][c] = true;
List<int[]> unities = new ArrayList<>();
int unity = 0;
int sum = 0;
while (!q.isEmpty()) {
int[] cur = q.poll();
int cr = cur[0];
int cc = cur[1];
for (int d = 0; d < 4; d++) {
int nr = cr + dr[d];
int nc = cc + dc[d];
if (nr < 0 || nc < 0 || nr >= N || nc >= N) continue;
if (visited[nr][nc]) continue;
int diff = Math.abs(map[nr][nc] - map[cr][cc]);
if (diff >= L && diff <= R) {
united = true;
if (unities.isEmpty()) {
unities.add(new int[]{cr, cc});
sum += map[cr][cc];
unity++;
}
unities.add(new int[]{nr, nc});
sum += map[nr][nc];
unity++;
q.add(new int[]{nr, nc});
visited[nr][nc] = true;
}
}
}
if (!unities.isEmpty()) {
int avg = sum / unity;
for (int[] u : unities) {
unitedMap[u[0]][u[1]] = avg;
}
}
}
}
- 국경 검사 누락 문제를 해결하는 방법은 생각보다 간단했다.
- 큐에 넣는 행위를 국경 개방 조건 안에 배치하면 끝이다.
- 만약 내 주위에 조건에 맞는 곳이 없다면 다음 BFS로 넘어가고, 조건에 맞는 곳이 있다면 그때 BFS를 시작하면 되는 것이었다.
- 또한 평균 계산도 united 값으로 하는 것이 아닌, 리스트가 비어 있는지에 따라 해야 했었다.
- 시간이 오래 측정되어서 GPT에게 풀이를 요청해 봤다.
GPT 풀이
import java.io.*;
import java.util.*;
public class Main {
static int N, L, R;
static int[][] map;
static boolean[][] visited;
static int[] dr = {0, 1, 0, -1};
static int[] dc = {1, 0, -1, 0};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
L = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
map = new int[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
int days = 0;
while (true) {
visited = new boolean[N][N];
boolean moved = false;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j]) {
if (bfs(i, j)) {
moved = true;
}
}
}
}
if (!moved) break; // 더 이상 이동이 없으면 종료
days++;
}
System.out.println(days);
}
static boolean bfs(int r, int c) {
Queue<int[]> queue = new LinkedList<>();
List<int[]> union = new ArrayList<>();
queue.add(new int[]{r, c});
union.add(new int[]{r, c});
visited[r][c] = true;
int totalPopulation = map[r][c]; // 연합의 총 인구 수
int countryCount = 1; // 연합을 이루는 나라 개수
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int cr = cur[0], cc = cur[1];
for (int d = 0; d < 4; d++) {
int nr = cr + dr[d];
int nc = cc + dc[d];
if (nr >= 0 && nr < N && nc >= 0 && nc < N && !visited[nr][nc]) {
int diff = Math.abs(map[cr][cc] - map[nr][nc]);
if (L <= diff && diff <= R) { // 국경 개방 조건
queue.add(new int[]{nr, nc});
union.add(new int[]{nr, nc});
visited[nr][nc] = true;
totalPopulation += map[nr][nc];
countryCount++;
}
}
}
}
if (union.size() == 1) return false; // 연합이 형성되지 않으면 false
// 인구 이동 실행 (연합 내 모든 나라 인구를 갱신)
int newPopulation = totalPopulation / countryCount;
for (int[] pos : union) {
map[pos[0]][pos[1]] = newPopulation;
}
return true;
}
}
- GPT도 나랑 거의 비슷한 형식으로 풀었다.
- 차이점
- 맵을 2개 사용하지 않았다는 점 → 첫 번째 시도의 내가 맞았었다.
- bfs의 결과로 boolean 값을 받아서 연합 여부 확인한 점
- 연합 리스트의 첫 번째 원소를 넣는 방식
- 비슷하게 푼 만큼 결과도 거의 비슷하게 나왔다.
- 아마 이게 가장 정석대로 푸는 방법인 듯하다.
BFS 내부 실행 조건을 잘 생각하자!!!
'오늘의 백준 문제' 카테고리의 다른 글
[오늘의 백준 문제] 2206번 벽 부수고 이동하기 - BFS (3차원) (0) | 2025.04.01 |
---|---|
[오늘의 백준 문제] 14499번 주사위 굴리기 - 구현, 시뮬레이션 (0) | 2025.03.31 |
[오늘의 백준 문제] 1759번 암호 만들기 - 백트래킹(조합) (0) | 2025.03.28 |
[오늘의 백준 문제] 14725번 개미굴 - 트리, 트라이, DFS (1) | 2025.03.26 |
[오늘의 백준 문제] 16236번 아기 상어 - BFS, 시뮬레이션 (1) | 2025.03.25 |