문제 링크
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근 방법
지금 시작하기로 한 과제시각과 그다음 시작해야 할 과제시각의 차를 구한 후,
지금 시작하는 과제시간과 위에서 구한 시간을 비교하며 과제를 끝낼 수 있는지 확인합니다.
과제를 끝나고 난 후에도 시간이 남는다면, 하다 멈춘 과제들을 하나씩 수행합니다.
소스 코드
#include <vector>
#include <stack>
#include <algorithm>
#include <tuple>
#include <string>
using namespace std;
bool comp(vector<string>& a, vector<string>& b)
{
return a[1] < b[1];
}
int intHour(string& hour)
{
return (stoi(hour.substr(0,2)) * 60 + stoi(hour.substr(3)));
}
vector<string> solution(vector<vector<string>> plans)
{
vector<string> answer;
stack<tuple<string, int>> s;
int sub, duration;
sort(plans.begin(), plans.end(), comp);
for (int i = 0; i < (int)(plans.size() - 1); i++)
{
sub = intHour(plans[i + 1][1]) - intHour(plans[i][1]);
duration = stoi(plans[i][2]);
if (sub >= duration)
{
sub -= duration;
answer.emplace_back(plans[i][0]);
}
else
{
s.emplace(plans[i][0], duration - sub);
continue;
}
while (!s.empty())
{
auto [name, tmpDuration] = s.top();
s.pop();
if (sub >= tmpDuration)
{
sub -= tmpDuration;
answer.emplace_back(name);
}
else
{
s.emplace(name, tmpDuration - sub);
break;
}
}
}
answer.emplace_back(plans.back()[0]);
while (!s.empty())
{
auto [name, tmpDuration] = s.top();
s.pop();
answer.emplace_back(name);
}
return answer;
}
코드 설명
intHour 함수는 string으로 된 현재 시각을 int형 분으로 바꿔주는 함수입니다.
과제 시작 시각으로 먼저 정렬을 합니다. 다음 과제 시작 시각과 현재 시각을 빼,
과제를 수행할 수 있는 시간부터 구해줍니다.
과제를 시간내에 수행할 수 없다면, 하다 남은 시간과 과제명을 스택에 넣습니다.
과제를 시간내에 수행한다면 answer에 넣어주며, 하다 남은 과제가 있는지 확인합니다.
남은 과제들을 시간 내에 수행한다면 answer에 넣습니다.
이 과정을 반복하면 맨 마지막 과제가 남습니다. 마지막 과제는 제한 시간이 없으므로
바로 answer에 넣어주며, 스택에 남아있는 과제들을 차례대로 answer에 넣어줍니다.
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스 JAVA] 181893. 배열 조각하기 (0) | 2024.06.01 |
---|---|
[프로그래머스 C++] 176963. 추억 점수 (0) | 2024.05.16 |
[프로그래머스 C++] 12906. 같은 숫자는 싫어 (0) | 2024.05.14 |
[프로그래머스 C++] 43165. 타겟 넘버 (0) | 2024.05.13 |
[프로그래머스 C++] 42586. 기능개발 (0) | 2024.05.13 |