N

(프로그래머스 c++) 붕대 감기 본문

프로그래머스 알고리즘/0 & 1단계

(프로그래머스 c++) 붕대 감기

naeunchan 2025. 10. 9. 18:18
728x90
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/250137#

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

0초부터 시작해서 공격을 받는 시간까지 for문을 돌면서 할 수 있겠지만,

덜 오래 걸리는 방식은 attacks만 순회하면 될 것 같다는 생각이 들었다.

 

current_time = 공격을 받는 사이의 시간을 알아내기 위한 변수.

current_health = 현재 체력.

taken_time, recovery, additional = bandage에 해당하는 값(시전 시간, 초당 회복량, 추가 회복량)

 

1. attacks를 순회하면서 체력 회복과 데미지를 current_health에 업데이트 한다.

2. 계산하기 쉽도록 attack_time, damage 변수를 선언.

    diff_time = 공격을 받기까지 걸린 시간

    quo = 시전 시간 동안 공격을 받았는지 확인하는 변수로 1 이상인 경우 추가 회복을 할 수 있다. diff_time - 1을 한 이유는 공격을 받을 때는 계산을 하지 않기 때문이다.

3. 먼저 현재 체력에 초당 회복량을 더해준다.

    조건은 diff_time > 1이고, current_health가 최대 체력을 넘지 않으면 회복을 한다.

    또한, 회복 시 추가 회복을 할 수 있으면 추가 회복량도 더해준다. 추가 회복의 조건은 quo가 1 이상, diff_time > taken_time인 경우다.

4. 현재 체력에 데미지를 빼준다. 만약 회복 후 체력이 최대 체력을 넘었으면, 최대 체력에서 데미지를 빼주고, 그렇지 않다면 현재 체력에서 데미지를 빼준다.

5. 현재 체력을 확인해서 0 이하인 경우, -1을 리턴, 그렇지 않으면 계속 진행한다. current_time도 현재 공격받은 time으로 업데이트를 해주면 된다.

#include <vector>

using namespace std;

int solution(vector<int> bandage, int health, vector<vector<int>> attacks) {
    int current_time = 0;
    int current_health = health;
    int taken_time = bandage[0];
    int recovery = bandage[1];
    int additional = bandage[2];
    
    for(auto attack : attacks) {
        int attack_time = attack[0];
        int damage = attack[1];
        
        int diff_time = attack_time - current_time;
        int quo = (diff_time - 1) / taken_time;
        
        // recovery
        if (diff_time > 1 && current_health <= health) {
            current_health += (recovery * (diff_time - 1));
            
            if (quo && diff_time > taken_time) {
                current_health += (additional * quo);
            }
        }
        
        // damage
        current_health = current_health >= health ? health - damage : current_health - damage;
        
        if (current_health <= 0) {
            return -1;
        }
        
        current_time = attack_time;
    }
    
    return current_health;
}
728x90
반응형