[백준] 16235. 나무 재테크 (자바 JAVA)

thsamajiki·2024년 3월 21일
0

문제

부동산 투자로 억대의 돈을 번 상도는 최근 N×N 크기의 땅을 구매했다. 상도는 손쉬운 땅 관리를 위해 땅을 1×1 크기의 칸으로 나누어 놓았다. 각각의 칸은 (r, c)로 나타내며, r은 가장 위에서부터 떨어진 칸의 개수, c는 가장 왼쪽으로부터 떨어진 칸의 개수이다. r과 c는 1부터 시작한다.

상도는 전자통신공학과 출신답게 땅의 양분을 조사하는 로봇 S2D2를 만들었다. S2D2는 1×1 크기의 칸에 들어있는 양분을 조사해 상도에게 전송하고, 모든 칸에 대해서 조사를 한다. 가장 처음에 양분은 모든 칸에 5만큼 들어있다.

매일 매일 넓은 땅을 보면서 뿌듯한 하루를 보내고 있던 어느 날 이런 생각이 들었다.

나무 재테크를 하자!

나무 재테크란 작은 묘목을 구매해 어느정도 키운 후 팔아서 수익을 얻는 재테크이다. 상도는 나무 재테크로 더 큰 돈을 벌기 위해 M개의 나무를 구매해 땅에 심었다. 같은 1×1 크기의 칸에 여러 개의 나무가 심어져 있을 수도 있다.

이 나무는 사계절을 보내며, 아래와 같은 과정을 반복한다.

봄에는 나무가 자신의 나이만큼 양분을 먹고, 나이가 1 증가한다. 각각의 나무는 나무가 있는 1×1 크기의 칸에 있는 양분만 먹을 수 있다. 하나의 칸에 여러 개의 나무가 있다면, 나이가 어린 나무부터 양분을 먹는다. 만약, 땅에 양분이 부족해 자신의 나이만큼 양분을 먹을 수 없는 나무는 양분을 먹지 못하고 즉시 죽는다.

여름에는 봄에 죽은 나무가 양분으로 변하게 된다. 각각의 죽은 나무마다 나이를 2로 나눈 값이 나무가 있던 칸에 양분으로 추가된다. 소수점 아래는 버린다.

가을에는 나무가 번식한다. 번식하는 나무는 나이가 5의 배수이어야 하며, 인접한 8개의 칸에 나이가 1인 나무가 생긴다. 어떤 칸 (r, c)와 인접한 칸은 (r-1, c-1), (r-1, c), (r-1, c+1), (r, c-1), (r, c+1), (r+1, c-1), (r+1, c), (r+1, c+1) 이다. 상도의 땅을 벗어나는 칸에는 나무가 생기지 않는다.

겨울에는 S2D2가 땅을 돌아다니면서 땅에 양분을 추가한다. 각 칸에 추가되는 양분의 양은 A[r][c]이고, 입력으로 주어진다.

K년이 지난 후 상도의 땅에 살아있는 나무의 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N, M, K가 주어진다.

둘째 줄부터 N개의 줄에 A배열의 값이 주어진다. r번째 줄의 c번째 값은 A[r][c]이다.

다음 M개의 줄에는 상도가 심은 나무의 정보를 나타내는 세 정수 x, y, z가 주어진다. 처음 두 개의 정수는 나무의 위치 (x, y)를 의미하고, 마지막 정수는 그 나무의 나이를 의미한다.

출력

첫째 줄에 K년이 지난 후 살아남은 나무의 수를 출력한다.

제한

  • 1 ≤ N ≤ 10
  • 1 ≤ M ≤ N2
  • 1 ≤ K ≤ 1,000
  • 1 ≤ A[r][c] ≤ 100
  • 1 ≤ 입력으로 주어지는 나무의 나이 ≤ 10
  • 입력으로 주어지는 나무의 위치는 모두 서로 다름

예제 입력 1

1 1 1
1
1 1 1

예제 출력 1

1

예제 입력 2

1 1 4
1
1 1 1

예제 출력 2

0

예제 입력 3

5 2 1
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 1 3
3 2 3

예제 출력 3

2

예제 입력 4

5 2 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 1 3
3 2 3

예제 출력 4

15

예제 입력 5

5 2 3
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 1 3
3 2 3

예제 출력 5

13

예제 입력 6

5 2 4
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 1 3
3 2 3

예제 출력 6

13

예제 입력 7

5 2 5
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 1 3
3 2 3

예제 출력 7

13

예제 입력 8

5 2 6
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 3 2 3 2
2 1 3
3 2 3

예제 출력 8

85



풀이

문제에서 시간이 다른 문제에 비해 넉넉하지 않은 편이기 때문에, 코드를 구현할 때 주의해야 합니다.
이 문제를 풀 때 처음에는 ArrayList로 접근했다가 몇 번 시간 초과 판정을 받았는데 다음과 같은 부분을 조심하면 될 것이다.

  1. ArrayList를 사용해서 구현을 한다면 매 년마다 정렬을 하지 말 것!
틀린 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

class Tree implements Comparable<Tree> {
    int x;
    int y;
    int age;

    public Tree(int x, int y, int age) {
        this.x = x;
        this.y = y;
        this.age = age;
    }

    @Override
    public int compareTo(Tree o) {
        return this.age - o.age;
    }
}

public class Main {
    static int N, M, K;
    static int[] dx = { -1, -1, 0, 1, 1, 1, 0, -1 };
    static int[] dy = { 0, 1, 1, 1, 0, -1, -1, -1 };
    static int[][] A, nutrientMap;
    static boolean[][] visited;
    static ArrayList<Tree> liveTrees;
    static ArrayList<Tree> deadTrees;

    public void spring() {
        int treeSize = liveTrees.size();

        for(int i = 0; i < treeSize; i++) {
            int x = liveTrees.get(i).x;
            int y = liveTrees.get(i).y;

            if (nutrientMap[x][y] >= liveTrees.get(i).age) {
                nutrientMap[x][y] -= liveTrees.get(i).age;
                liveTrees.get(i).age++;
            } else {
                deadTrees.add(liveTrees.get(i));
                liveTrees.remove(liveTrees.get(i));
            }
            treeSize = liveTrees.size();
        }
    }

    public void summer() {
        for(Tree tree: deadTrees) {
            int x = tree.x;
            int y = tree.y;
            nutrientMap[x][y] += tree.age / 2;
        }
    }

    public void autumn() {
        ArrayList<Tree> babyTrees = new ArrayList<>();
        for(Tree tree: liveTrees) {
            if (tree.age % 5 == 0) {
                for (int i = 0; i < 8; i++) {
                    int nextX = tree.x + dx[i];
                    int nextY = tree.y + dy[i];

                    if (nextX < 0 || nextX > N - 1 || nextY < 0 || nextY > N - 1) continue;

                    babyTrees.add(new Tree(nextX, nextY, 1, false));
                }
            }
        }

        liveTrees.addAll(babyTrees);
    }

    public void winter() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                nutrientMap[i][j] += A[i][j];
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken()); // 땅의 가로, 세로 크기
        M = Integer.parseInt(st.nextToken()); // 심은 나무의 개수
        K = Integer.parseInt(st.nextToken()); // 시간(년)이 얼마나 지났는지

        A = new int[N][N]; // 각 칸에 추가되는 양분의 양
        nutrientMap = new int[N][N]; // 각 칸에 이미 있는 양분의 양

        liveTrees = new ArrayList<>();
        deadTrees = new ArrayList<>();
        visited = new boolean[N][N];

        for(int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                A[i][j] = Integer.parseInt(st.nextToken());
                nutrientMap[i][j] = 5;
            }
        }

        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            int z = Integer.parseInt(st.nextToken());
            liveTrees.add(new Tree(x - 1, y - 1, z, false));
        }

        while (K --> 0) {
            deadTrees = new ArrayList<>();
            main.spring();
            main.summer();
            main.autumn();
            main.winter();
        }

        System.out.println(liveTrees.size());
    }
}

  1. ArrayList의 경우 remove()할 때, 배열 내부의 값이 갱신될 수 있으므로 주의할 것!
    틀린 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

class Tree implements Comparable<Tree> {
    int x;
    int y;
    int age;

    public Tree(int x, int y, int age) {
        this.x = x;
        this.y = y;
        this.age = age;
    }

    @Override
    public int compareTo(Tree o) {
        return this.age - o.age;
    }
}

public class Main {
    static int N, M, K;
    static int[] dx = { -1, -1, 0, 1, 1, 1, 0, -1 };
    static int[] dy = { 0, 1, 1, 1, 0, -1, -1, -1 };
    static int[][] A, nutrientMap;
    static ArrayList<Tree> liveTrees;
    static ArrayList<Tree> deadTrees;

    public void spring() {
        Collections.sort(liveTrees);
        ArrayList<Tree> cloneTrees = new ArrayList<>(liveTrees);

        for(int i = 0; i < cloneTrees.size(); i++) {
            int x = cloneTrees.get(i).x;
            int y = cloneTrees.get(i).y;

            if (nutrientMap[x][y] >= cloneTrees.get(i).age) {
                nutrientMap[x][y] -= cloneTrees.get(i).age;
                cloneTrees.get(i).age++;
            } else {
                deadTrees.add(cloneTrees.get(i));
                liveTrees.remove(cloneTrees.get(i));
            }
        }
    }

    public void summer() {
        for(Tree tree: deadTrees) {
            int x = tree.x;
            int y = tree.y;
            nutrientMap[x][y] += tree.age / 2;
        }
    }

    public void autumn() {
        ArrayList<Tree> babyTrees = new ArrayList<>();
        for(Tree tree: liveTrees) {
            if (tree.age % 5 == 0) {
                for (int i = 0; i < 8; i++) {
                    int nextX = tree.x + dx[i];
                    int nextY = tree.y + dy[i];

                    if (nextX < 0 || nextX > N - 1 || nextY < 0 || nextY > N - 1) continue;

                    babyTrees.add(new Tree(nextX, nextY, 1));
                }
            }
        }

        liveTrees.addAll(babyTrees);
    }

    public void winter() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                nutrientMap[i][j] += A[i][j];
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken()); // 땅의 가로, 세로 크기
        M = Integer.parseInt(st.nextToken()); // 심은 나무의 개수
        K = Integer.parseInt(st.nextToken()); // 시간(년)이 얼마나 지났는지

        A = new int[N][N]; // 각 칸에 추가되는 양분의 양
        nutrientMap = new int[N][N]; // 각 칸에 이미 있는 양분의 양

        liveTrees = new ArrayList<>();
        deadTrees = new ArrayList<>();

        for(int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                A[i][j] = Integer.parseInt(st.nextToken());
                nutrientMap[i][j] = 5;
            }
        }

        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            int z = Integer.parseInt(st.nextToken());
            liveTrees.add(new Tree(x - 1, y - 1, z));
        }
        
        while (K --> 0) {
            deadTrees = new ArrayList<>();
            main.spring();
            main.summer();
            main.autumn();
            main.winter();
        }

        System.out.println(liveTrees.size());
    }
}


2개의 시행착오를 거치면서 풀이 전략을 고민해봤다.

1의 경우, 나이에 따라 오름차순 정렬되는데 매 년 sort를 하지 않고 자동 정렬되도록 PriorityQueue로 대체했다.
2의 경우, PriorityQueue 타입의 temp 임시 변수를 만들어서 원소값들을 순회하도록 했고 마지막에 살아있는 나무 목록에 대입하여 Swapping되도록 했다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

class Tree implements Comparable<Tree> {
    int x;
    int y;
    int age;

    public Tree(int x, int y, int age) {
        this.x = x;
        this.y = y;
        this.age = age;
    }

    @Override
    public int compareTo(Tree o) {
        return this.age - o.age;
    }
}

public class Main {
    static int N, M, K;
    static int[] dx = { -1, -1, 0, 1, 1, 1, 0, -1 };
    static int[] dy = { 0, 1, 1, 1, 0, -1, -1, -1 };
    static int[][] A, nutrientMap;
    static PriorityQueue<Tree> liveTrees;
    static ArrayList<Tree> deadTrees;

    public void spring() {
        PriorityQueue<Tree> cloneTrees = new PriorityQueue<>();

        while(!liveTrees.isEmpty()) {
            Tree nowTree = liveTrees.poll();
            int x = nowTree.x;
            int y = nowTree.y;

            if (nutrientMap[x][y] >= nowTree.age) {
                cloneTrees.offer(new Tree(x, y, nowTree.age + 1));
                nutrientMap[x][y] -= nowTree.age;
            } else {
                deadTrees.add(nowTree);
            }
        }

        liveTrees = new PriorityQueue<>(cloneTrees);
    }

    public void summer() {
        for(Tree tree: deadTrees) {
            int x = tree.x;
            int y = tree.y;
            nutrientMap[x][y] += tree.age / 2;
        }
    }

    public void autumn() {
        PriorityQueue<Tree> tempTrees = new PriorityQueue<>();
        while (!liveTrees.isEmpty()) {
            Tree nowTree = liveTrees.poll();
            tempTrees.offer(nowTree);

            if (nowTree.age % 5 == 0) {
                for (int i = 0; i < 8; i++) {
                    int nextX = nowTree.x + dx[i];
                    int nextY = nowTree.y + dy[i];

                    if (nextX < 0 || nextX > N - 1 || nextY < 0 || nextY > N - 1) continue;

                    tempTrees.offer(new Tree(nextX, nextY, 1));
                }
            }
        }

        liveTrees = new PriorityQueue<>(tempTrees);
    }

    public void winter() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                nutrientMap[i][j] += A[i][j];
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Main main = new Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken()); // 땅의 가로, 세로 크기
        M = Integer.parseInt(st.nextToken()); // 심은 나무의 개수
        K = Integer.parseInt(st.nextToken()); // 시간(년)이 얼마나 지났는지

        A = new int[N][N]; // 각 칸에 추가되는 양분의 양
        nutrientMap = new int[N][N]; // 각 칸에 이미 있는 양분의 양

        liveTrees = new PriorityQueue<>();
        deadTrees = new ArrayList<>();

        for(int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                A[i][j] = Integer.parseInt(st.nextToken());
                nutrientMap[i][j] = 5;
            }
        }

        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            int z = Integer.parseInt(st.nextToken());
            liveTrees.add(new Tree(x - 1, y - 1, z));
        }

        while (K --> 0) {
            deadTrees = new ArrayList<>();
            main.spring();
            main.summer();
            main.autumn();
            main.winter();
        }

        System.out.println(liveTrees.size());
    }
}



후기

시뮬레이션 문제인데 생각보다 시간 초과를 해결하는데 오래 걸렸으니 익숙해지도록 노력해야겠다!

profile
안드로이드 개발자

0개의 댓글