Java

[PCCP 기출문제] 1번 / 붕대 감기

Daeryuk Kim 2023. 12. 8. 18:39
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        int[] bandage = {3, 2, 7};
        int health = 20;
        int[][] attacks = {{1, 15}, {5, 16}, {8, 6}};

        Solution sol = new Solution();

        int result = sol.solution(bandage, health, attacks);

        System.out.println(result);
    }

    public int solution(int[] bandage, int health, int[][] attacks) {
        // 끝나는 시간
        int endTime = attacks[attacks.length - 1][0];
        // 최대 체력
        int maxHealth = health;
        // 공격 시간을 나타내는 맵
        Map<Integer, Integer> attackMap = new HashMap<>();
        for (int[] attack : attacks) {
            attackMap.put(attack[0], attack[1]);
        }
        // 연속 시간
        int successTime = 1;

        for (int time = 1; time <= endTime; time++) {
            // 공격을 당할 경우
            if (attackMap.containsKey(time)) {
                successTime = 1;
                health -= attackMap.get(time);
                if (health <= 0) {
                    return -1;
                }
            // 공격 안당하는 경우
            } else {
                health = Math.min(maxHealth, health + bandage[1]);
                if (successTime == bandage[0]) {
                    health = Math.min(maxHealth, health + bandage[2]);
                    successTime = 1;
                } else {
                    successTime += 1;
                }
            }
        }

        return health;
    }
}

파이썬 힌트 보고 고쳤다.

아래는 다른 사람의 코드다.

간단한 산술식 그 자체다. 

코드는 이렇게 간결하고 클린하게 짜야함을 새삼 배운다.  

import java.util.*;

class Solution {

    public int solution(int[] bandage, int health, int[][] attacks) {
        int cnt = bandage[0]; // 추가 체력 기준
        int now = health; // 현재 체력
        int std = 0; // 마지막으로 공격당한 시간

        int v1, v2; // 추가 체력 받을 수 있나?
        for (int[] atk: attacks) {
            if (now <= 0) {
                return -1;
            }

            v1 = atk[0] - std - 1; // 시간 차이
            v2 = v1 / cnt; // 추가 체력 회수

            // 맞기 직전까지의 체력 정산
            std = atk[0];
            now = Math.min(health, now + (v1 * bandage[1]));
            now = Math.min(health, now + (v2 * bandage[2]));

            now -= atk[1];
        }        

        return now <= 0 ? -1 : now;
    }
}