오늘의 알고리즘
[C++]탐욕법(Greedy) 구명보트(프로그래머스 2레벨)
하늘하늘 .
2022. 4. 14. 16:40
#include <string>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> people, int limit)
{
// 맨 뒤를 limit을 넘기 직전까지 추가한 뒤
// 맨 앞을 추가해주면 limit을 최대만큼
// 추가할 수 있지 않을까라는 생각으로 짯다
int answer = 0;
sort(people.begin(), people.end());
list<int> peopleList = {};
// 앞 뒤만 접근하기 위해 List 사용
for (int i = 0; i < people.size(); ++i)
{
peopleList.push_back(people[i]);
}
while (!peopleList.empty())
{
int iMax = 0;
while (iMax < limit)
{
// 없을 경우 패스
if (peopleList.empty())
break;
// 맨 뒤를 추가
iMax += peopleList.back();
// 추가한게 limit보다 크다면 패스
if (iMax > limit)
{
iMax -= peopleList.back();
break;
}
// 아니라면 다음으로
else
peopleList.pop_back();
}
while (iMax < limit)
{
// 없을 경우 패스
if (peopleList.empty())
break;
// 맨 앞을 추가
iMax += peopleList.front();
// 추가한게 limit보다 크다면 패스
if (iMax > limit)
{
iMax -= peopleList.front();
break;
}
// 아니라면 다음으로
else
peopleList.pop_front();
}
++answer;
}
return answer;
}
이게 왜 탐욕법인지는 모르겠다.
그리고 문제에서 2명이라는 걸 못 봤는데... 이게 왜 된거지?
나중에 문제가 변경되면 실패할수도?