[프로그래머스] 붕대 감기
Programmers - [PCCP 기출문제] 1번 / 붕대 감기
사용 언어 - C++
소요 시간 - 약 40분
문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/250137
문제 요약
- 1초마다 x만큼 체력 회복
- 정해진 시간만큼 연속으로 회복에 성공하면 추가 회복
- 현재체력 ≤ 최대체력
- 중간에 공격 당하면 회복 취소, 연속 회복 시간 초기화
- 사망 시 return -1
최종 코드
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> bandage, int health, vector<vector<int>> attacks) {
int answer = 0;
int currentTime = 0;
int consecution = 0;
answer = health;
for(int time = 1; time <= attacks[attacks.size() - 1][0]; time++)
{
if(attacks[currentTime][0] == time)
{
answer -= attacks[currentTime][1];
currentTime++;
if(answer <= 0)
return -1;
consecution = 0;
continue;
} //피격 우선 처리(피격 시 회복이 되지 않아야 하기 때문)
//일반 회복
if(answer + bandage[1] >= health)
answer = health;
else
answer += bandage[1];
consecution++;
if(consecution == bandage[0]) //추가 회복
{
if(answer + bandage[2] >= health)
answer = health;
else
answer += bandage[2];
consecution = 0;
}
}
return answer;
}
트러블 슈팅
- 최대 체력 이상으로 회복 되었을 때, 현재 체력 값을 최대 체력 값으로 초기화 시켜주지 않아 결과 값이 예상 값보다 높게 출력됨
- 최대 체력을 넘는 경우, continue를 해서 추가적인 회복이 불가능이 되어 오류가 발생
- 당시 코드
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> bandage, int health, vector<vector<int>> attacks) {
int answer = 0;
int currentTime = 0;
int consecution = 0;
answer = health;
for(int time = 1; time <= attacks[attacks.size() - 1][0]; time++)
{
if(attacks[currentTime][0] == time)
{
answer -= attacks[currentTime][1];
currentTime++;
if(answer <= 0)
return -1;
consecution = 0;
continue;
}
if(answer + bandage[1] >= health)
{
answer = health;
continue;
}
answer += bandage[1];
consecution++;
if(consecution == bandage[0])
{
if(answer + bandage[2] >= health)
{
answer = health;
continue;
}
answer += bandage[2];
}
}
return answer;
}
-
연속 성공 완료 시, 추가로 체력이 회복되고 연속 성공 시간을 초기화 해야 하는데, 초기화 하지 않아 이후로 연속 성공이 정상적으로 이루어지지 않음
-
당시 코드
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> bandage, int health, vector<vector<int>> attacks) {
int answer = 0;
int currentTime = 0;
int consecution = 0;
answer = health;
for(int time = 1; time <= attacks[attacks.size() - 1][0]; time++)
{
if(attacks[currentTime][0] == time)
{
answer -= attacks[currentTime][1];
currentTime++;
if(answer <= 0)
return -1;
consecution = 0;
continue;
}
if(answer + bandage[1] >= health)
answer = health;
else
answer += bandage[1];
consecution++;
if(consecution == bandage[0])
{
if(answer + bandage[2] >= health)
answer = health;
else
answer += bandage[2];
}
}
return answer;
}